Reputation: 884
I'm using drf to create API view like this:
{
"name": "some name",
"attribute1": "some attribute",
"attribute2": "some attribute",
"attribute3": "some attribute",
"attribute4": "some attribute",
"stats": {
"status": false,
"count": 0
}
}
stats
field is created as serializer (OneToOneField in models), but sometimes there is no object associated in this OneToOne relation so stats
is null
.
Problem is I want to order my queryset by f.e. stats__count
. Ascending order of this sorting is working. count = 0
is at the beggining and nulls are at the end, but when I want to sort it in descending order I want to have biggest value of this attribute at the beggining. I'm getting all the nulls instead.
Question is: how to place this elements with stats = null
at the end of result or at least remove them from queryset (but only when ordering by field from stats
).
Upvotes: 0
Views: 766
Reputation: 798
Best bet is to use annotate() as described in this SO question: Django : Order by position ignoring NULL
items = Item.objects.all().annotate(null_position=Count('position')).order_by('-null_position', 'position')
Upvotes: 1