[Fixed]-In Django ORM, "values" and "annotate" are not working to group by

60👍

(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

Leave a comment