python - 预取查询集不能使用值
问题描述
我想进行以下查询以获取具有此特征的查询集:
- 预过滤
- 按名称分组
- 对内部数据求和
在我的代码中,我有:
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
解决方案
您可以删除对原始查询的 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
later 的值。
推荐阅读
- python - 抓取脚本具有完整性属性的 JS 渲染网页
- javascript - 如何在组件中监听 redux 动作流
- prolog - 如何在 Prolog 中表示情况演算?
- java - 如何修复maven中俄语编码的错误?
- grafana - 具有相关字段但标签不同的 promql 示例
- swift - 如何使用 gzip 将我从蓝牙低功耗设备获取的压缩 .gz 文件转换为 Swift 4.2 中的实际解压缩文件?
- typescript - 覆盖迭代器签名
- r - Blogdown kable 表格格式(丑陋)
- crystal-reports - 组页脚 - 页面底部显示在中间
- python - 如何在 google colab 上仅加载特定文件夹?