R.J. Jackson
R.J. Jackson

Reputation: 125

Django-Getting most recent entry before today

I'm trying to get the most recent entry before today's date. I tried to go about it like this:

query = my_table.objects.filter(~Q(date__gt=datetime.date.today()))
recent = query[-1]

However it doesn't allow negative splicing. I'm not quite sure the best way to go about this.

Upvotes: 1

Views: 1177

Answers (1)

catavaran
catavaran

Reputation: 45575

Order the queryset by date in reverse order and then get the first record:

recent = my_table.objects.filter(date__lt=datetime.date.today()) \
                         .order_by('-date').first()

Or you can use the latest() method but it will raise DoesNotExist in case if there is no such record in database (first() in this case will return None):

recent = my_table.objects.filter(date__lt=datetime.date.today()) \
                         .latest('date')

Upvotes: 3

Related Questions