Django ORM 中的替代 nullif

Voi*_*ray 2 django django-models

使用 Postgres 作为数据库和 Django 1.9

我有一些带有“价格”字段的模型。“价格”空白=真。在 ListView 上,我得到查询集。接下来,我想按价格排序,最后价格=0。

我如何用 SQL 编写: 'ORDER BY NULLIF('price', 0) NULLS LAST'

Django ORM 上怎么写?或者在rawsql上?

Voi*_*ray 8

好的。我找到了替代方案。使用 django func 编写自己的 NullIf。

from django.db.models import Func

class NullIf(Func):
    template = 'NULLIF(%(expressions)s, 0)'
Run Code Online (Sandbox Code Playgroud)

并将其用于查询集:

queryset.annotate(new_price=NullIf('price')).order_by('new_price')
Run Code Online (Sandbox Code Playgroud)

编辑:Django 2.2 及更高版本已经实现了开箱即用。等效的代码将是

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')
Run Code Online (Sandbox Code Playgroud)