matt matt - 1 year ago 121
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 Source

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']))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download