Pierre
Pierre

Reputation: 47

How can I get the latest date using Django?

Hello I have this query :

myObject.objects.filter(id=id, date=date).distinct('start').order_by('start')

In my table I have only as fields : id, date, start and end. date, start and end are datetime type.

The problem is that I would like to get in the end the latest date not a random date when I did the distinct on the field start. How can I do this ?

Thank you very much !

Upvotes: 1

Views: 296

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can order by end in descending order as a tie breaker if the start is the same:

myObject.objects.filter(
    id=id, date=date
).distinct('start').order_by('start', '-end')

That being said, if you filter on id=id, then it will likely contain at most one record, so it is a bit "odd", that you filter on the id here.

Upvotes: 1

Related Questions