我想在注释查询集中添加比较操作来计算特定字段的值。我怎样才能做到这一点? 这是我的注释查询集
'
上面的查询集的条件表达式运行错误。请帮我解决一下吗?
答案 0 :(得分:3)
尝试使用小于和大于字段的查找__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
答案 1 :(得分:1)
这里是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, ...