Queryset序列化:AttributeError:'dict'对象没有属性'_meta' [英] Queryset Serialize: AttributeError: 'dict' object has no attribute '_meta'

查看:320
本文介绍了Queryset序列化:AttributeError:'dict'对象没有属性'_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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆