Correlated Subqueries with Django's ORM

zep*_*iyr 5 python django django-filter correlated-subquery django-rest-framework

Is there a way to model a correlated subquery using Django's ORM? Did I overlook this in the documentation somewhere?

I'm using Python 3.3, Django 1.7, and Django REST Framework 3.0.0. This is all against a legacy database - Django Models are in Managed = False mode.

In one of my ModelViewSets, I'm trying to set queryset. If I were writing SQL, what I need is:

select * from table
where dateField = (
    select max(dateField)
    from table lookup
    where lookup.varField = table.varField
)
Run Code Online (Sandbox Code Playgroud)

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

The ModelViewSet works if I give it a RawQuerySet (model.objects.raw()) with the above query, but then I can't filter using filter_fields in my ModelViewSet.

I've gotten results that are somewhat close by using annotate:

TableModel.objects.values('varField').annotate(dateField=Max('dateField')).filter(varField='aString')
Run Code Online (Sandbox Code Playgroud)

However, I need all the columns from table, and if I just use values() the ORM puts every field in its GROUP BY clause, whereas I only need varField in the GROUP BY.

Could someone point me in the right direction? Thanks in advance.