user10421193
user10421193

Reputation: 217

Objects with the lowest value 0 at the end

The 0 in my query set represent 'unknown' values, but when ordered, they start the list and I want them at the end.

table.objects.filter(object=pk).order_by('decimal_coln')

This is what I'm getting

Object        decimal_coln
Object_kdlsdl 0
Object_nksljj 0
Object_njsdlk 0
Object_jdnskl 1
Object_ldskll 1
Object_nlsdkl 12
Object_sjslkl 15

This is what I want (ordered, but zeros at the end):

Object        decimal_coln
Object_jdnskl 1
Object_ldskll 1
Object_nlsdkl 12
Object_sjslkl 15
Object_kdlsdl 0
Object_nksljj 0
Object_njsdlk 0

Upvotes: 0

Views: 147

Answers (2)

Mukul Kumar
Mukul Kumar

Reputation: 2103

You just need to import F from django.db.models and use in order by column:

from django.db.models import F
table.objects.filter(object=pk).order_by(F('decimal_coln').desc(nulls_last=True))

Upvotes: 0

JPG
JPG

Reputation: 88499

Use asc() expression - [Djangodoc]

Returns the expression ready to be sorted in ascending order.

nulls_first and nulls_last define how null values are sorted


from django.db.models import F

order_by_expression = F('decimal_coln').asc(nulls_last=True)
table.objects.filter(object=pk).order_by(order_by_expression)

Example can be found here

Upvotes: 1

Related Questions