Skip to main content
 首页 » 编程设计

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

2024年08月22日30www_RR

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

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

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

请您参考如下方法:

尝试使用小于和大于字段查找 __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