预取查询集不能使用值

2024-09-29 19:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

要查询以下特征:

  1. 预过滤
  2. 按名称分组
  3. 对内部数据求和

在我的代码中我有:

q = DatiBanca.objects\
   .filter(is_negativo=False)\
   .values("istituto_credito__name")\
   .order_by("istituto_credito__name")

anagrafiche = anagrafiche.prefetch_related(
   Prefetch('dati__banche', queryset=q)
)

数据集JSON:

^{pr2}$

此查询显示以下错误:

“预取查询集不能使用values()。”

如何从数据集中得到以下结果?在

"dataset": {
    "id": 40,
    "banche": [
        {
        "name": "Pippo",
        "importo": "30",
        "istituto_credito": 3,
        "is_negativo": false
        }
        {
        "name": "Pluto",
        "importo": "40",
        "istituto_credito": 5,
        "is_negativo": false
        },
        {
        "name": "Paperino",
        "importo": "50",
        "istituto_credito": 4,
        "is_negativo": false
        }
    ]
}

this example: How to combine django “prefetch_related” and “values” methods? 不要使用预取函数并将结果限制为一个字段。我想对Anagrafica的sub queryset执行分组操作

我使用 django 2.1.5款


Tags: 数据djangonamefalseisquerysetvaluesrelated
1条回答
网友
1楼 · 发布于 2024-09-29 19:06:04

您只需删除对原始查询的values()调用,如下所示:

q = DatiBanca.objects\
   .filter(is_negativo=False)\
   .order_by("istituto_credito__name")

anagrafiche = anagrafiche.prefetch_related(
   Prefetch('dati__banche', queryset=q)
)

现在,anagrafiche中的每个对象都是一个DatiBlanca对象,并预取了DatiBlanca.dati.banche。然后,您可以稍后从这个查询集中列出DatiBlanca.istituto_credito.name的值。在

相关问题 更多 >

    热门问题