使用字典值更新查询集

Vai*_*hav 3 python django dictionary django-queryset

我正在编写自定义列表过滤器和内部过滤器调用,我有一个Django 查询集,如下所示

查询集 =[qs1, qs2, qs3]

对于查询集中的所有对象,查询集具有属性Count_val = 0,UUID =(唯一 id)

所以可以说

qs1 = {uuid: 123, count_val: 0}

qs2 = {uuid: 456, count_val: 0}

qs1 = {uuid: 789, count_val: 0}

我有一本像 {uuid: count_val} 的字典

示例 {123: 5, 456: 10, 789: 15 }

我想在返回查询集作为响应之前更新所有对象的查询集属性 count_values

也许注释,但我如何为每个值提取每个 uuid

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
Run Code Online (Sandbox Code Playgroud)

感谢帮助

Iai*_*ton 5

您可以创建与字典中每个键匹配的对象列表When并返回值。然后将此列表解压缩为Case对象的位置参数

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)))
Run Code Online (Sandbox Code Playgroud)