Reputation: 18691
Given following model:
class MyModel(models.Model):
date = models.DateField()
comments = models.CharField(max_length=16)
Containing following records:
1/May/2016: a
20/May/2016: b
3/Nov/2016: c
15/Nov/2016: d
I would like to get the latest record up to a certain date, e.g. latest_up_to_date(18/August/2016)
should return b
.
Upvotes: 0
Views: 49
Reputation: 1544
date_val = datetime.datetime.strptime('1/Aug/2016', '%d/%b/%Y')
MyModel.objects.filter(date__lte=date_val).latest('date')
Upvotes: 1
Reputation: 18691
Exclude the newer objects first, and then use latest()
:
latest_up_to_date = None
try:
latest_up_to_date = MyModel.objects.exclude(date__gt=datetime.date(2016, 8, 18)).latest('date')
except MyModel.DoesNotExist:
pass
Upvotes: 1