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

2.6k views Asked by At

Imagine I have this Django model:

class Letter(models.Model):
    name = models.CharField(max_length=1, unique=True)

and too this list:

vowels = ['a', 'e', 'i', 'o', 'u']

I want to make a query over Letter annotating a boolean field, which will be True if name value is in vowels list, and False otherwise.

I made next query:

from django.db.models import Value, F, BooleanField

letters = Letter.objects.annotate(
    is_vowel=Value(F('name') in vowels, output_field=BooleanField())
)

However no matter what letters I analyze, the result is ALWAYS False What am I doing wrong in my query, and what is the correct way to achieve the desired result? Thanks in advance.

2

There are 2 answers

0
Ogulcan Olguner On

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()
               ),
            )
0
Ivan Cvetković On

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())
)