问题
I'm having trouble transferring my query to django. In sqlite3 it looked like this:
SELECT A, MIN(B), MAX(B) from table GROUP BY A
This would output unique values from A with a range of values from B Any hints on how to approach this? Is it even possible in django?
回答1:
You can use values()
for the GROUP BY
, and annotate()
for the MIN
and MAX
:
from django.db.models import Min, Max
MyModel.objects.values('A').annotate(min_b=Min('B'), max_b=Max('B'))
You'll get a list of dictionaries, containing the keys A
, min_b
and max_b
.
来源:https://stackoverflow.com/questions/32561631/django-query-model-group-by-min-max