我需要在多个 DateTimeFields 中查找最新的日期条目。
模型.py:
class Presentation(models.Model):
start = models.DateTimeField(blank=True, null=True, verbose_name=_(u'Start'))
end = models.DateTimeField(blank=True, null=True, verbose_name=_(u'End'))
我知道latest()遗憾的是,它只支持查询单个字段。
编辑:我正在寻找一种单查询解决方案(如果存在)。
最佳答案
对于一个查询解决方案,您可以使用 django 的 extra()查询集方法:
latest_obj = Presentaion.objects.extra({"latest_date":"greatest(start, end)"}).order_by('latest_date')[0]
这将为您提供具有最新时间戳的对象。 latest_obj
现在有一个额外的属性 latest_date
latest_obj.latest_date
编辑:
不建议使用 extra()
,并且将在未来版本中弃用。
Use this method as a last resort. This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods.
django1.9中的一个数据库函数Greatest
被介绍了。现在您可以使用 annotate
来实现:
from django.db.models.functions import Greatest
latest_obj = Presentaion.objects.annotate(last_date=Greatest('start', 'end')).order_by('last_date')[0]
关于Django 查询多个日期中的最新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943232/