[Answered ]-Why using .last() on distincted queryset gives me object with was not primary in queryest?

1👍

What you want is a GROUP BY clause.

In Plain SQL you would write something like

SELECT bid_date, MAX(bid) 
FROM bids
GROUP BY bid_date 
ORDER BY bid_count DESC;

In Django you could use aggregations or annotations, but aggregate clauses are terminal whereas if you use annotations, it will return a QuerySet on which you can use the first() and last() calls.

Bid.objects \
.values('bid_date') \
.annotate(Max('bid_count')) \
.order_by('bid_count__max') \
.last()

This is a helpful article on group by queries in Django: https://simpleisbetterthancomplex.com/tutorial/2016/12/06/how-to-create-group-by-queries.html

Leave a comment