Correlated subqueries with Django ORM

Is there a way to model a correlated subquery using Django ORM? Have I missed this in the documentation somewhere?

I am using Python 3.3, Django 1.7 and Django REST Framework 3.0.0. It all has to do with a legacy database - Django models are in Managed = False

.

In one of mine ModelViewSets

, I am trying to install queryset

. If I was writing SQL, then I need:

select * from table
where dateField = (
    select max(dateField)
    from table lookup
    where lookup.varField = table.varField
)

      

I will also need to execute .filter () in this query (adding fields to the WHERE clause in the outer query).

ModelViewSet

works if I give it RawQuerySet

( model.objects.raw()

) with the above query, but then I cannot filter with filter_fields

in ModelViewSet

.

I got some close results using annotate

:

TableModel.objects.values('varField').annotate(dateField=Max('dateField')).filter(varField='aString')

      

However, I want all the columns from the table, and if I just use values()

, the ORM puts each field in its clause GROUP BY

, whereas I only need varField

to GROUP BY

.

Can anyone point me in the right direction? Thanks in advance.

+3


source to share





All Articles