Reputation: 786
i have a datetime field which can be null and id like to do qs.order_by('field__isnull', 'name') but this results in:
Join on field 'field' not permitted. Did you misspell 'isnull' for the lookup type?
Is this possible at all?
Upvotes: 9
Views: 2574
Reputation: 1261
Unfortunately, Django doesn't provide function IsNull
, that could be used for ordering, annotations, etc.
(It does provide a query lookup, but it may only be used for filtering.)
You may however define the function yourself:
from django.db.models import BooleanField, Func
class IsNull(Func):
_output_field = BooleanField()
arity = 1
template = '%(expressions)s IS NULL'
Now you may order your queryset like this:
qs.order_by(IsNull('field'), 'name')
Upvotes: 7
Reputation: 3793
I'm hoping that your model is something like this:
date_deleted = models.DateTimeField(blank=True, null=True)
If True then you can do this:
qs.order_by('-date_deleted')
Upvotes: -3
Reputation: 28637
there may be better ways, but one possibility is to annotate your queryset:
from django.db.models import Count
qs.annotate(null_count=Count('field_name')).order_by('null_count')
Upvotes: 12