参见https://docs.djangoproject.com/en/dev/ref/models/conditional-expressions/ 条件表达式与Case;
o = Object.annotate(
custom_price=Case(
When(price=1, then=Value(2)),
default=0,
output_field=DecimalField(),
)
)
如何使用set'default' - Object的当前值? 现在它只写为const:0
想要类似的东西:
if price =1:
custom_price = 2
else:
custom_price = Object.price
答案 0 :(得分:1)
F
用于执行此操作。因此,您的代码应如下所示:
from django.db.models import Case, F, Value, When, DecimalField
o = Object.objects.annotate(custom_price=Case(
When(price=1, then=Value(2)),
default=F('price'),
output_field=DecimalField(),
)
)