[英]How to make a conditional query in Django?
我正在尝试按计算字段进行过滤,其中计算取决于其他字段的值。
我正在尝试按sales_price
(计算字段)过滤,其中sales_price
的定义如下伪代码
if discount is NULL
sales_price = price
else
sales_price = price - price*discount/100
最终目标是按范围过滤sales_price
:
filter(sales_price__range=(price_min, price_max))
这是我的模型:
class Product(models.Model):
price = models.IntegerField()
discount = models.IntegerField(blank=True, null=True)
我只会指出你正确的方向:
When
和Case
的条件表达式中使用F
表达式您想按依赖于其他值的值进行排序,因此让我们在条件表达式中使用F 表达式(因为sales_price
依赖于其他字段)(因为最终表达式取决于discount
是否为NULL
)
首先,我们构造一个依赖于discount
和price
的sales_price
值,并用它来注释我们的查询:
from django.db.models import When, Case, F, IntegerField
Product.objects.annotate(
sales_price=Case(
When(discount__isnull=True, then=F('price')),
When(discount__isnull=False, then=(F('price') - (F('discount') * F('price')) / 100)),
output_field=IntegerField(),
)
)
现在,您已经包含了一个sales_price
,您可以使用它进行过滤:
Product.objects.annotate(...).filter(sales_price__range=(price_min, price_max)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.