[Django]-Django annotate a Boolean if field value is in an external list

6👍

You can use the following query. django doc conditional expressions

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

letters = Letter.objects.annotate(
              is_vowel=Case(
                  When(name__in=vowels, then=Value(True)),
                  default=Value(False),
                  output_field=BooleanField()
               ),
            )

6👍

Django query expressions do not support in operator, but you can use ExpressionWrapper:

letters = Letter.objects.annotate(
    is_vowel=ExpressionWrapper(Q(name__in=vowels), output_field=BooleanField())
)

Leave a comment