Queryset Serialize:AttributeError:“dict”对象没有属性“\u meta”

2024-04-26 21:28:18 发布

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

我试图将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}]>


Tags: 对象jsonbyobjectscountorderallstructure
2条回答

你可以试试:

import json
from django.core.serializers.json import DjangoJSONEncoder

qs = Fund.objects.values('structure').annotate(total=Count('structure')).order_by('-total')
structure = json.dumps(list(qs), cls=DjangoJSONEncoder)

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',))

相关问题 更多 >