我有一个可以为空的日期时间字段,并且 id 喜欢做 qs.order_by('field__isnull', 'name') 但这会导致:
Join on field 'field' not permitted. Did you misspell 'isnull' for the lookup type?
这可能吗?
可能有更好的方法,但一种可能性是注释您的查询集:
from django.db.models import Count
qs.annotate(null_count=Count('field_name')).order_by('null_count')
不幸的是,Django 不提供IsNull
可用于排序、注释等的 function (它确实提供了查询查找,但它可能仅用于过滤。)但是您可以自己定义函数:
from django.db.models import BooleanField, Func
class IsNull(Func):
_output_field = BooleanField()
arity = 1
template = '%(expressions)s IS NULL'
现在您可以像这样订购您的查询集:
qs.order_by(IsNull('field'), 'name')
我希望你的模型是这样的:
date_deleted = models.DateTimeField(blank=True, null=True)
如果 True 那么你可以这样做:
qs.order_by('-date_deleted')