Search code examples
djangopostgresqldjango-modelsdjango-3.1

select branch_id from report group by branch_id order by max(date) desc to Django Query


I have a model with the following fields

id -> int

vivitor_id -> int

branch_id -> int

date -> datetime

I need to perform the following query in Django. How to do this using Django ORM.

select branch_id from report group by branch_id order by max(date) desc ;

Solution

  • You should use proper Aggregation with values as documented so something in a line of

    Report.objects.values('branch_id') 
        .annotate(max_date= Max('date'))
        .order_by('-max_date')