Django ORM, GROUP BY + MAX()

Viewed 42
SELECT date, name, MAX(broom) 
FROM brooms
GROUP BY name;

How do I submit this request to Django ORM? I realized that the answer will be in the form of dict, but in the end I only get fields named 'name' and 'broom__max', how do I add 'date' there?

class Brooms(models.Model):
    name = models.CharField(max_length=600)
    broom = models.PositiveIntegerField(verbose_name="broom")
    date= models.DateTimeField(auto_now_add=True, db_index=True)

I tried such a query

Brooms.objects.values('name').annotate(Max('broom'))

But I can't add 'date' to SELECT, if I add 'date' to values(), 'date' falls into GROUP BY

1 Answers

Try it:

Brooms.objects.values_list('date','name').annotate(Max('broom')).values('date','name','broom')
Related