Django 查询多个日期中的最新日期

标签 django django-queryset

我需要在多个 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/

相关文章:

django - 修改查询集结果

django - 如何过滤Django的CommaSeparatedIntegerField

python - 在 django 中使用 select_lated 无法获取其他属性的值

Django:使用 Django ORM 实现 JOIN?

python - Django 自定义注解函数

Django通过子模型计数(一对多关系)对父模型进行排序

javascript - Django + Javascript + "onmouseover"

Django如何写PositiveDecimalField

python - 从foreignkey中过滤属于用户的所有对象

python - 我如何将这些多重连接作为 Django 查询集进行?