2

I have a model class with a status field, which might have several alternatives, say:

class MyModel(models.Model):
    status_choices = (
        ('status1', 'status1'),
        ('status2', 'status2'),
        ('status3', 'status3'),
        ('status4', 'status4'),
    )
    status = models.CharField(choices=status_choices)

Then I want to annotate the instances with an active field which might be either True or False. The instance is active when status is IN [status1, status2].

Django version is 1.11.

1 Answer 1

2

We can do this with a Case expression [Django-doc]:

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

MyModel.objects.annotate(
    active=Case(
        When(status__in=['status1', 'status2'], then=Value(True))
        default=Value(False),
        output_field=BooleanField()
    )
)

Note that the list of the status__in condition should contain the keys of the choices (so the left item of the tuples, not the right one).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.