【问题标题】:Django: how to add compare condition in annotate querysetDjango:如何在注释查询集中添加比较条件
【发布时间】:2016-10-06 14:32:49
【问题描述】:

我想在注释查询集中添加比较操作来计算特定字段的值。我怎样才能做到这一点? 这是我的注释查询集

sale_item_list = OrderItem.objects.filter(order_id=order.id) \
                .values('item__name') \
                .annotate(price=F('price')) \
                .annotate(exchange_rate=F('exchange_rate')) \
                .annotate(quantity=F('quantity') \
.annotate(amount=Case(
                        When(F('quantity') < F('inventory'), then=Sum(F('quantity') * F('price'))),
                        When(F('quantity') > F('inventory'), then=Sum(F('inventory') * F('price'))),
                        output_field=IntegerField()))

上面我的查询集的条件表达式运行错误。请帮我解决一下?

【问题讨论】:

标签: python django python-3.x


【解决方案1】:

尝试使用小于和大于字段查找__gt__lt

When(quantity__lt=inventory, then=Sum(F('quantity') * F('price'))),
When(quantity__gt=inventory, then=Sum(F('inventory') * F('price'))),

https://docs.djangoproject.com/el/1.10/ref/models/querysets/#gt

【讨论】:

    【解决方案2】:

    这里是Django的解决方案> 1.8为两个字段添加注释比较相等。

    queryset.annotate(
        is_custom=models.ExpressionWrapper(
            models.Q(field1__exact=models.F("field2")),
            output_field=models.BooleanField(),
        )
    )
    

    SQL 等价物

    SELECT field1 = field2 AS is_custom, ...
    

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 2013-08-28
      • 1970-01-01
      • 2018-05-29
      • 2016-08-17
      相关资源
      最近更新 更多