Django query model - GROUP BY, MIN, MAX

梦想与她 提交于 2020-01-03 16:57:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!