There is a model

class Bid(...): contractor = ... pub_date = ... ... 

The database is represented in this way

 id | contractor | pub_date 1 | 1 | 2016-08-20 2 | 1 | 2016-08-21 3 | 1 | 2016-08-30 4 | 2 | 2016-08-20 5 | 2 | 2016-08-29 

Need to get the latest entry for each contractor .

As far as I understand, this is done in SQL simply (SQL is not sure of my knowledge, but it seems that this query works, as I need):

 SELECT id, MAX(pub_date), contractor FROM bid GROUP BY contractor; 

Displays:

  id | contractor | pub_date 3 | 1 | 2016-08-30 5 | 2 | 2016-08-29 

And how to do it with the help of Django ORM?

    1 answer 1

    As far as I know, it is impossible to get the exact same result using ORM. The closest way:

      Bid.objects.values('contractor').annotate(latest_date=Max('pub_date')) 
    • This query displays only the contractor and the latest_date , and I was just interested in the id entity that corresponds to this relation. Anyway, thanks. - Alexey Solyony
    • As I wrote, this is the only way to group in Django ORM. - Sergey Gornostaev 1:01 pm