Create calculated column with if expression django

Viewed 36

I want to create a new calculated column on my django queryset (Models.objects) that will be calculated as:

field_one if field_one is not null else field two

I've tried some like this in django:

from models.models import Model
from django.db.models import F

data = Model.objects.annotate(start_date= F('better_date') if F('better_date') is not None else F('field_2'))
data[0].__dict__['start_date']
# Result
#'start_date': None

But I get a 'start_date' attribute as None

How do I create the column mentioned to use later while iterating the objects?

1 Answers

You can use When and Case Conditional Expressions in your annotations to make if statements

    from django.db.models import F, Case, When, Q, DateField
    data = your_model_name.objects.annotate(start_date=Case(
        When(
            condition=Q(better_date__isnull=False),
            then=F('better_date')
        ),
        default=F('field_2'),
        output_field=DateField(),
    ))
Related