Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative nullif in Django ORM

Use Postgres as db and Django 1.9

I have some model with field 'price'. 'Price' blank=True. On ListView, I get query set. Next, I want to sort by price with price=0 at end.

How I can write in SQL it: 'ORDER BY NULLIF('price', 0) NULLS LAST'

How write it on Django ORM? Or on rawsql?

like image 946
VoidArray Avatar asked Dec 19 '25 00:12

VoidArray


1 Answers

Ok. I found alternative. Write own NullIf with django func.

from django.db.models import Func

class NullIf(Func):
    template = 'NULLIF(%(expressions)s, 0)'

And use it for queryset:

queryset.annotate(new_price=NullIf('price')).order_by('new_price')

Edit : Django 2.2 and above have this implemented out of the box. The equivalent code will be

from django.db.models.functions import NullIf
from django.db.models import Value
queryset.annotate(new_price=NullIf('price', Value(0)).order_by('new_price')
like image 85
VoidArray Avatar answered Dec 20 '25 18:12

VoidArray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!