Queryset序列化:AttributeError:'dict'对象没有属性'_meta' [英] Queryset Serialize: AttributeError: 'dict' object has no attribute '_meta'
问题描述
我试图将queryset
作为JSON
对象传递:
I am trying to pass a queryset
as a JSON
object:
structure=Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total')
但是,querysets
不是Json Serializable
,因此,我修改了代码:
structure=Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total')
However, querysets
aren't Json Serializable
therefore, I modified my code:
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}]>
But I get this error: AttributeError: 'dict' object has no attribute '_meta'
and this is my queryset: <QuerySet [{'total': 106, 'structure': 'Corp'}, {'total': 43, 'structure': 'Trust'}, {'total': 2, 'structure': 'OM'}, {'total': 0, 'structure': None}]>
推荐答案
Django核心序列化程序只能序列化queryset
.但是values()
不会返回queryset
,而是返回ValuesQuerySet
对象.您可以在serialize()
方法中指定要在values()
中使用的字段,如下所示:
Django core serializers can only serialize a queryset
. But values()
doesn't return queryset
, rather a ValuesQuerySet
object. You can specifiy the fields you wish to use in values()
in the serialize()
method as follows:
from django.core import serializers
funds = Fund.objects.all().annotate(total=Count('structure')).order_by('-total')
structure = serializers.serialize('json', funds, fields=('structure',))
这篇关于Queryset序列化:AttributeError:'dict'对象没有属性'_meta'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!