Search code examples
pythondjangodjango-querysetannotatedjango-annotate

django annotate with dynamic "then" value


So i have this dictionary of months below:

MONTHS = {
    1: "Janeiro",
    2: "Fevereiro",
    3: "Março",
    4: "Abril",
    5: "Maio",
    6: "Junho",
    7: "Julho",
    8: "Agosto",
    9: "Setembro",
    10: "Outubro",
    11: "Novembro",
    12: "Dezembro",
}

And i want to annotate each of this value in a queryset, conditionally. I know i can use Case and When for that, and so am i, by doing:

queryset = queryset.annotate(
    last_installment_month_as_string=Case(
        When(last_installment_month=1, then=Value(MONTHS[1])),
        When(last_installment_month=2, then=Value(MONTHS[2])),
        When(last_installment_month=3, then=Value(MONTHS[3])),
        When(last_installment_month=4, then=Value(MONTHS[4])),
        When(last_installment_month=5, then=Value(MONTHS[5])),
        When(last_installment_month=6, then=Value(MONTHS[6])),
        When(last_installment_month=7, then=Value(MONTHS[7])),
        When(last_installment_month=8, then=Value(MONTHS[8])),
        When(last_installment_month=9, then=Value(MONTHS[9])),
        When(last_installment_month=10, then=Value(MONTHS[10])),
        When(last_installment_month=11, then=Value(MONTHS[11])),
        When(last_installment_month=12, then=Value(MONTHS[12])),
    )
)

But can't i do it dynamically? Like in a for loop or something? I tried doing on a for loop, but no success whatsoever...

Im looking to do something like:

for key, value in MONTHS.items():
    queryset = queryset.annotate(
    last_installment_month_as_string=Case(
        When(last_installment_month=key, then=Value(value)) 
    )
)

But that doesn't work!


Solution

  • Yes, you can work with:

    queryset = queryset.annotate(
        last_installment_month_as_string=Case(
            *[
                When(last_installment_month=key, then=Value(value))
                for key, value in MONTHS.items()
            ]
        )
    )