[Django]-Django ORM: Group by and Max

30👍

from django.db.models.aggregates import Max

request_values = Requests.objects.filter(req_text='YES') \
                 .values('user') \
                 .annotate(max_id=Max('id'))

Then request_values will look like this:

[
    {'user': 1, 'max_id': 1},
    {'user': 2, 'max_id': 4},
    {'user': 3, 'max_id': 5},
    {'user': 4, 'max_id': 12},
    ...
]

Leave a comment