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?
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With