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()))
我上面查询集的条件表达式运行错误。请帮我修好吗?
尝试使用小于和大于字段查找__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
这是 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, ...
| 归档时间: | 
 | 
| 查看次数: | 2508 次 | 
| 最近记录: |