我正在尝试通过 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/