matt matt - 1 month ago 14
SQL Question

Use a Max inside a Q query in Django

I am using Django Q objects to automatize the construction of complex queries from a textual description.

In some of my queries, I need to combine classic Q queries, with Max operator as in:

Book.objects.filter(Q(....) & Q(...) ....).aggregate(Max('price'))


Is there a way to express the Max filter as a Q() filter, so that I can use a simple chain of:

filter(Q(...) & Q(...) & Qmax(...))


which would be more convenient in the frame of my query-generator algorithm

Answer

You can write your query like this :

from django.db.models import Max
from django.db.models import Q

query = Book.objects.all().aggregate(Max('price'))

And use this result to further filter your queryset :

query_set = Book.objects.filter(Q(...) & Q(...) & Q(price= query['price__max']))