2017-09-05 44 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) 
相關問題