我有一个datetime字段,可以为null,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')
Run Code Online (Sandbox Code Playgroud)
不幸的是,Django 不提供IsNull可用于排序、注释等的 function 。(它确实提供了查询查找,但可能仅用于过滤。)但是您可以自己定义该函数:
from django.db.models import BooleanField, Func
class IsNull(Func):
_output_field = BooleanField()
arity = 1
template = '%(expressions)s IS NULL'
Run Code Online (Sandbox Code Playgroud)
现在您可以像这样订购查询集:
qs.order_by(IsNull('field'), 'name')
Run Code Online (Sandbox Code Playgroud)