Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A min function in query set Django to find the earlier date in a model?

I have a model that where each entry has a date. How do I use queryset to find the entry with the earliest date? This is not dependent on 'pk' because I could add a row with an earlier date at a later time.

This is what I have so far and it doesn't seem to work:

Model.objects.get(min(date))

Thanks.

like image 1000
H C Avatar asked Dec 22 '15 22:12

H C


2 Answers

Model.objects.earliest('date')
like image 77
Alex Polekha Avatar answered Oct 18 '22 17:10

Alex Polekha


earliest = Model.objects.order_by('date')[0]

You need to handle the case where there's no objects in Model though.

like image 32
Shang Wang Avatar answered Oct 18 '22 19:10

Shang Wang