Back to Articles
2024-02-20

SQL If/Else Logic with Case and When

Sometimes you need to label data based on complex conditions without looping through it in Python. The `Case` and `When` expressions allow you to implement SQL `CASE` statements directly in Django.

Scenario 1: Labeling Data

Create a 'segment' label based on spending amount.

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

customers = Customer.objects.annotate(
    segment=Case(
        When(total_spent__gt=1000, then=Value('VIP')),
        When(total_spent__gt=500, then=Value('Regular')),
        default=Value('New'),
        output_field=CharField(),
    )
)

Scenario 2: Custom Sorting Order

Sort by status in a specific order: Pending -> Processing -> Done.

python
from django.db.models import Case, When, Value, IntegerField

orders = Order.objects.annotate(
    custom_order=Case(
        When(status='Pending', then=Value(1)),
        When(status='Processing', then=Value(2)),
        When(status='Done', then=Value(3)),
        output_field=IntegerField(),
    )
).order_by('custom_order')