Django conditional annotation using python variable

Trying to figure out a way to use annotation depending of python variable condition check.

Example:

some_variable = 10000,50 #float

expenses_by_categories = (
            Category.objects.filter(transactions__operation="expenses")
            .annotate(
                expenses_sum=Sum('transactions__value', filter=Q(
                    transactions__date_created__month=datetime.date.today().month) & Q(
                    transactions__date_created__year=datetime.date.today().year)),
            )
            .annotate(
                percentage=Round(
                    ExpressionWrapper(
                    F('expenses_sum') / some_variable * 100, output_field=FloatField()
                    ), 2))
            .order_by('-percentage')
        )

It works as long as some_variable greater then 0 otherwise zero devision exception rised. Is there is a way to carry out some checks inside annotation with such a logic:

if some_variable > 0:
    percentage = F('expenses_sum') / some_variable * 100
else:
    percentage = 0

You can use Case with When to avoid the zero division exception in the annotation.

from django.db.models import Case, When

queryset.annotate(
    percentage=Round(
        Case(
            When(some_variable=0, then=0),
            default=ExpressionWrapper(F('expenses_sum') / some_variable * 100, output_field=FloatField()),
        ),
        2,
    )
)

Conditional Expressions Documentation

Back to Top