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

Voi*_*ray 3 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(),
                )
            )
Run Code Online (Sandbox Code Playgroud)

如何使用设置“默认”-对象的当前值?现在它只写为 const: 0

想要类似的东西:

if price =1:
    custom_price = 2
else:
    custom_price = Object.price
Run Code Online (Sandbox Code Playgroud)

Moh*_*eem 10

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(),
            )
        )
Run Code Online (Sandbox Code Playgroud)