如何在Django中实现合并查询?

2024-04-19 20:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用django和django rest框架构建一个ecom网站。我的模型项目包含“价格”和“销售价格”列:

class Item(models.Model):
    price = models.FloatField()
    sale_price = models.FloatField(null=True,blank=True)

我想按最大有效价格过滤它们 因此,为了在sqlite中实现这一点,我将编写如下内容

SELECT * FROM item WHERE coalesce(sale_price,price) < maxPrice;

在Django我怎么做


Tags: 项目django模型框架resttrue网站models
1条回答
网友
1楼 · 发布于 2024-04-19 20:25:42

Django有一个^{} [Django-doc]函数。因此,您可以过滤,例如:

from django.db.models.functions import Coalesce

Item.objects.annotate(
    real_price=Coalesce('sale_price', 'price')
).filter(
    real_price__lt=maxPrice
)

或者,如果您想要两个中最大的一个,最好使用:

from django.db.models.functions import Coalesce

Item.objects.annotate(
    real_price=Greatest(Coalesce('sale_price', 'price'), 'price')
).filter(
    real_price__lt=maxPrice
)

在最大表达式中处理NULL的方式因数据库而异。例如,SQLite将在其中一个参数为NULL时返回NULL

相关问题 更多 >