因此,在我的 Django 项目中,我创建了一个通知模型,它有两个日期时间字段,一个是时间戳,一个是截止日期。截止日期是可选的。现在我有一个通知列表,有些有截止日期,有些没有。它们都有一个时间戳。我想做的是使用具有该字段的通知的截止日期和没有该可选字段的通知的时间戳对列表中的它们进行排序。正如您所看到的,我使用两个字段作为键有点奇怪,但它们都是日期时间字段。所以我认为他们应该能够进行比较。
我的代码:
class Notifications(models.Model):
date = models.DateTimeField(auto_now=True)
title = ...
content = ...
due_date = models.DateTimeField(null=True, blank=True)
最佳答案
您想要使用 SQL COALESCE
:
The
COALESCE
function accepts a list of parameters, returning the first non-Null value from the list:
我认为 django 没有聚合函数,但你可以这样做:
Notifications.objects.filter(**some_filter_args)
.extra(select={"sortdate" : 'COALESCE("due_date", "date")'})
.order_by("-sortdate")
关于python - 我试图组契约(Contract)一对象的两个列表,在 python 中使用不同的字段但相同类型的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11786964/