首页 > 解决方案 > 预取查询集不能使用值

问题描述

我想进行以下查询以获取具有此特征的查询集:

  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:

"dataset": {
    "id": 40,
    "banche": [
        {
        "id": 18396,
        "name": "Pippo",
        "importo": "10",
        "istituto_credito": 3,
        "is_negativo": false
        },
        {
        "id": 18397,
        "name": "Pippo",
        "importo": "20",
        "istituto_credito": 3,
        "is_negativo": false
        },
        {
        "id": 18398,
        "name": "Pippo",
        "importo": "999999999999",
        "istituto_credito": 3,
        "is_negativo": true
        },
        {
        "id": 16519,
        "name": "Pluto",
        "importo": "40",
        "istituto_credito": 5,
        "is_negativo": false
        },
        {
        "id": 13967,
        "name": "Paperino",
        "importo": "50",
        "istituto_credito": 4,
        "is_negativo": false
        }
    ]
}

这个查询给了我以下错误:

“预取查询集不能使用 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
        }
    ]
}

这个例子:如何结合 django “prefetch_related” 和 “values” 方法? 不要使用 Prefetch 函数并将结果限制为一个字段。我想对 Anagrafica 的子查询集执行分组操作

我使用 django 2.1.5

标签: pythondjangoorm

解决方案


您可以删除对原始查询的 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.namelater 的值。


推荐阅读