M
M
MOV_UA2019-11-30 16:55:45
Django
MOV_UA, 2019-11-30 16:55:45

Is it possible to use the F function like this?

Messages.objects.annotate(new_field=Value(('a1' if F('id') in [1755, 1753] else 'a2'), output_field=CharField()))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Fomin, 2019-11-30
@MOV_UA

No. In this case, you need to use Conditional Expressions. Example:

from django.db.models import CharField, Value, Case, When

Messages.objects.annotate(
    new_field=Case(
        When(id__in=[1755, 1753], then=Value('a1')),
        default=Value('a2'),
        output_field=CharField()
    )
)

If a1 and a2 are not values, but fields, then you need to replace Value with F

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question