Django:如何在annotate查询集中添加比较条件

10

我希望在annotate queryset中添加比较操作以计算特定字段的值。我该怎么做?

这是我的annotate queryset:

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()))

我的查询集中的条件表达式运行出错了,能帮我修复一下吗?


相关链接:https://dev59.com/r5_ha4cB1Zd3GeqPwUzs - djvg
2个回答

7

6

以下是解决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, ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接