8

我有一个可以为空的日期时间字段,并且 id 喜欢做 qs.order_by('field__isnull', 'name') 但这会导致:

Join on field 'field' not permitted. Did you misspell 'isnull' for the lookup type?

这可能吗?

4

3 回答 3

11

可能有更好的方法,但一种可能性是注释您的查询集:

from django.db.models import Count
qs.annotate(null_count=Count('field_name')).order_by('null_count')
于 2012-03-10T18:20:20.547 回答
4

不幸的是,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')
于 2020-07-07T09:13:23.767 回答
-3

我希望你的模型是这样的:

    date_deleted = models.DateTimeField(blank=True, null=True)

如果 True 那么你可以这样做:

qs.order_by('-date_deleted')
于 2012-03-10T18:23:40.117 回答