[英]How can i implement coalesce query in django?
I'm trying to build an ecom website using django and djngo rest framework.我正在尝试使用 django 和 djngo rest 框架构建一个电子商务网站。 My model Item contains price and sale_price column:
我的 model 项目包含 price 和 sale_price 列:
class Item(models.Model):
price = models.FloatField()
sale_price = models.FloatField(null=True,blank=True)
I want to filter them by max active price So in order to do that in sqlite i would write something like我想按最大有效价格过滤它们所以为了在 sqlite 中做到这一点,我会写类似
SELECT * FROM item WHERE coalesce(sale_price,price) < maxPrice;
How can i do this in Django?我如何在 Django 中做到这一点?
Django has a Coalesce
[Django-doc] function. Django 有一个
Coalesce
[Django-doc] function。 You thus can filter for example on:因此,您可以过滤例如:
from django.db.models.functions import
Coalesce
Item.objects.annotate(
real_price=
Coalesce('sale_price', 'price'
)
).filter(
real_price__lt=maxPrice
)
or if you want the largest of the two, it is best to use:或者如果你想要两者中最大的一个,最好使用:
from django.db.models.functions import
Coalesce
Item.objects.annotate(
real_price=
Greatest(Coalesce('sale_price', 'price'), 'price'
)
).filter(
real_price__lt=maxPrice
)
The way NULL
s are handled in a greatest expression differ from database to database. NULL
的处理方式因数据库而异。 For example SQLite will return NULL
from the moment one of the parameters is NULL
.例如 SQLite 将从参数之一为
NULL
NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.