截至某个日期的最新记录

时间:2016-11-25 20:42:06

标签: django

给出以下模型:

class MyModel(models.Model):
    date = models.DateField()
    comments = models.CharField(max_length=16)

包含以下记录:

1/May/2016: a
20/May/2016: b
3/Nov/2016: c
15/Nov/2016: d

我想获得某个日期的最新记录,例如latest_up_to_date(18/August/2016)应该返回b

2 个答案:

答案 0 :(得分:1)

首先排除较新的对象,然后使用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

答案 1 :(得分:1)

date_val = datetime.datetime.strptime('1/Aug/2016', '%d/%b/%Y')    
MyModel.objects.filter(date__lte=date_val).latest('date')