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

tre*_*dez 6 python django python-3.x

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

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

我上面查询集的条件表达式运行错误。请帮我修好吗?

Elw*_*ens 6

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

When(quantity__lt=inventory, then=Sum(F('quantity') * F('price'))),
When(quantity__gt=inventory, then=Sum(F('inventory') * F('price'))),
Run Code Online (Sandbox Code Playgroud)

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


suq*_*ant 6

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

queryset.annotate(
    is_custom=models.ExpressionWrapper(
        models.Q(field1__exact=models.F("field2")),
        output_field=models.BooleanField(),
    )
)
Run Code Online (Sandbox Code Playgroud)

SQL 等效项

SELECT field1 = field2 AS is_custom, ...
Run Code Online (Sandbox Code Playgroud)