Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM - Dynamically add When to Case

I have a list of lists

my_list= [
    [1,2,3],
    [4,5,6],
    ...
]

I'd like to annotate some values like this:

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

MyModel.objects.filter(...).annotate(label=Case(When(some_value__in=my_list[0] then=Value('first list')), output_field=CharField()))

Now I need add a similar When for the other lists in my_list, but my_list could have different lengths.

How could I do this?

like image 553
Gocht Avatar asked Oct 21 '25 11:10

Gocht


1 Answers

A Case expression can contain any number of Whens. You can create a list of When expressions and then unpack it into a Case:

whens = [When(some_value__in=l, then=Value('list #{}'.format(i)))\
            for i, l in enumerate(my_list)]

MyModel.objects.filter(...).annotate(label=Case(*whens, output_field=CharField()))
like image 63
Ivan Avatar answered Oct 25 '25 07:10

Ivan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!