[Answered ]-Django ORM: Ordering w/ aggregate functions — None special treatment

2👍

How about just adding a has_something=1,0 via extra() and then order on both has_something and something?

with_avg = SomeObject.objects.annotate(avg=Avg('something'))
with_avg_and_has = with_avg.extra(select={'has_something': 'something is NULL'})
sorted_result = with_avg_and_has.order_by('-has_something', '-avg').all() 

Not 100% ORM in the strictest sense but it does push the sorting back into the DB.

Leave a comment