django order by isnull value?

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')

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')

Tags:

Django

Isnull