Django order items by two fields, but ignoring them if they're zero

早过忘川 提交于 2019-12-04 00:50:03

You could use the extra() QuerySet method to create an extra field in your query using the COALESCE function in SQL, which returns the first non-NULL value it's passed.

Product.objects.extra(select={"current_price":"COALESCE(sale_price, price)"}, order_by=["-current_price"])

You have to put your order_by in the extra() call as the extra manual field "doesn't really exist" as far as the rest of the ORM is concerned, but the syntax is the same as normal Django order_by()s.

See the extra() documentation here: http://docs.djangoproject.com/en/1.3/ref/models/querysets/#extra

If you stumble upon this requirement and happen to be using Django 1.8 and higher, you can use django.db.models.functions.Coalesce for a slightly nicer, cross db-engine, solution:

from django.db.models.functions import Coalesce

Product.objects.annotate(
    current_price=Coalesce('sale_price', 'price')
).order_by('-current_price')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!