python - 查询集序列化 : AttributeError: 'dict' object has no attribute '_meta'

标签 python json django

我正在尝试通过 queryset作为JSON对象:

structure=Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total') 然而,querysets不是Json Serializable因此,我修改了我的代码:

from django.core import serializers


structure=serializers.serialize('json',Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total'))

但我收到此错误:AttributeError: 'dict' object has no attribute '_meta'这是我的查询集:<QuerySet [{'total': 106, 'structure': 'Corp'}, {'total': 43, 'structure': 'Trust'}, {'total': 2, 'structure': 'OM'}, {'total': 0, 'structure': None}]>

最佳答案

Django 核心序列化器只能序列化 queryset。但 values() 不会返回 queryset,而是返回 ValuesQuerySet 对象。您可以在 serialize() 方法的 values() 中指定要使用的字段,如下所示:

from django.core import serializers

funds = Fund.objects.all().annotate(total=Count('structure')).order_by('-total')
structure = serializers.serialize('json', funds, fields=('structure',))

关于python - 查询集序列化 : AttributeError: 'dict' object has no attribute '_meta' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062242/

相关文章:

python - Django:在保存模型时检测一组字段的变化

json - 使用 powershell 删除变量内的循环

python - 外壳错误 : doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

python - 谷歌分析 API 问题

python - 与用户输入的数字比较总是产生 "not equal"结果

json - 将 JSON 数据从一个表插入到 HIVE 中的另一个表

javascript - 如何将函数绑定(bind)到 JSON 对象?

python - 使用 SelectDateWidget 的 Django 表单字段

django - 通过 django-widget-tweaks 使用字段标签作为占位符

python - 无法使用 python 脚本更改 docker 容器内的工作目录