如何在Django上使用对象的默认值进行条件表达式?

时间:2017-02-24 18:25:13

标签: django django-models

参见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

1 个答案:

答案 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(),
            )
        )