[Django]-Update queryset with dictionary values

5👍

You can create a list of When objects that match each key in the dictionary and return the value. Then unpack this list into positional arguments to the Case object

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

whens = [When(uuid=k, then=Value(v)) for k, v in dictionary.items()]
queryset = queryset.annotate(count_val=Case(*whens, output_field=IntegerField(), default=Value(0)))

0👍

Let the query set be qs and dictionary be d

qs2=qs[:]
for elem in qs2:
    qs2["count_val"] = d[elem["uuid"]]
return qs2

Leave a comment