In Django ORM, “values” and “annotate” are not working to group by

删除回忆录丶 提交于 2019-12-03 12:49:16

(The answer is hidden in the comments, so I've turned it into a proper answer. I spend a few hours having the same problem.)

The key problem is that Django automatically adds the fields you sort on to values(). So in your case, you think you're doing .values('date_of_meal'). But because of the ordering = ['-updated', '-timestamp'] on your model, django turns it into `.values('date_of_meal', 'updated', 'timestamp') instead...

With such an unexpected .values() you of course don't get the group_by behaviour you expect.

The solution is to "reset" the default ordering by either adding an empty .order_by() or, in your case, .order_by('date_of_meal').

See the django documentation

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