【问题标题】:How to make a conditional query in Django?如何在 Django 中进行条件查询?
【发布时间】:2016-06-10 15:41:44
【问题描述】:

我正在尝试按计算字段进行过滤,其中计算取决于其他字段的值。

我正在尝试按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)                                                                             

【问题讨论】:

  • 您是否将 GET 参数转换为整数?
  • price1 是否低于 price2?
  • 是的,它低于 price2
  • 我在上面转换为 int 检查
  • 如何查询该范围内的sales_price

标签: python django django-orm


【解决方案1】:

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

在带有WhenCase 的条件表达式中使用F 表达式

您想按依赖于其他值的值排序,所以让我们在conditional expression 中使用F Expression(因为sales_price 依赖于其他字段)(因为最终表达式取决于discount 是否为NULL与否)

首先,我们构造一个依赖于discountpricesales_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)

【讨论】:

  • 全局名称'IntegerField'未定义
  • 治愈了较早的一个..但是想出了这个无法将关键字“sales_price”解析到字段中
  • 我认为 F('sales_price') 不是模型的一部分
  • 我可以进一步注释它以从查询集中获取最小和最大价格 minprice = queryset.annotate(Min('sales_price')) maxprice = queryset.annotate(Max('sales_price'))
猜你喜欢
  • 2020-06-04
  • 2011-09-27
  • 2015-09-25
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
相关资源
最近更新 更多