Update queryset with dictionary values

Viewed 531

I am writing custom List filter and inside filter call i have a Django queryset as below

queryset =[qs1, qs2, qs3]

queryset have a attribute Count_val = 0, UUID = (unique id) for all objects in queryset

so lets say

qs1 = {uuid: 123, count_val: 0}

qs2 = {uuid: 456, count_val: 0}

qs1 = {uuid: 789, count_val: 0}

Also

I have a dictionary like {uuid: count_val}

example {123: 5, 456: 10 , 789: 15 }

I want to update queryset attribute count_values for all objects before returning queryset as response

Maybe annotate but how i pull each uuid for each value

queryset=queryset.annotate(count_val = Case(When(uuid_in=dictionary.keys(), then=dictionary[uuid]), field_type=Integer))   ## not correct syntax just an example
# inserting to new field is also fine
#queryset.extra(value={count_val : dictionary[uuid]})
return queryset

Thanks for help

2 Answers

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)))

Let the query set be qs and dictionary be d

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