如何在Django中进行条件查询

Adi*_*ngh 3 python django django-orm

我试图通过计算字段进行过滤,其中计算取决于其他字段的值.

我正在尝试过滤sales_price(计算字段),其中sales_price定义如下伪代码

if discount is NULL                                                             
    sales_price = price                                                         
else                                                                            
    sales_price = price - price*discount/100 
Run Code Online (Sandbox Code Playgroud)

最终目标是sales_price按范围过滤:

filter(sales_price__range=(price_min, price_max))                                   
Run Code Online (Sandbox Code Playgroud)

这是我的模型:

class Product(models.Model):                                                
  price = models.IntegerField()                                             
  discount = models.IntegerField(blank=True, null=True)                                                                             
Run Code Online (Sandbox Code Playgroud)

bak*_*kal 6

我只会指出你正确的方向:

使用F表达式在条件表达式WhenCase

你想依赖于其他值的值进行排序,让我们用一个˚F表达(因为sales_price在一个依赖于其他领域的)条件表达式(因为最终的表达依赖于是否discountNULL与否)

首先,我们构造一个sales_price取决于价值discountprice,并用它诠释我们的查询:

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

现在有了这个,你已经包含了一个sales_price可以过滤的:

   Product.objects.annotate(...).filter(sales_price__range=(price_min, price_max)
Run Code Online (Sandbox Code Playgroud)