Skip to content Skip to sidebar Skip to footer

In Django Orm, "values" And "annotate" Are Not Working To Group By

I have a table like this: Now I want to sum up the meals on each date. I have written the code below. But it doesn't work as I wanted. Model: class Meal(models.Model): user =

Solution 1:

(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

Post a Comment for "In Django Orm, "values" And "annotate" Are Not Working To Group By"