2017-09-05 43 views
1

我想传递一个querysetJSON对象:查询集序列化:AttributeError的:“快译通”对象有没有属性“_meta”

structure=Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total') 然而,querysetsJson 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}]>

+0

豆:https://stackoverflow.com/a/9061105/1571826 –

+0

试了一下已经使用'only'没没有工作。 – anderish

+0

尝试将您的查询集(剥离到值字典)放入顶级字典中,如{'thing':the_queryset}并序列化该对象。有时序列化程序不会让你序列化一个类似列表的东西,因为安全性。 – theWanderer4865

回答

2

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

from django.core import serializers 

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

你可以尝试:

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) 
相关问题