【问题标题】:Queryset Serialize: AttributeError: 'dict' object has no attribute '_meta'查询集序列化:AttributeError:“dict”对象没有属性“_meta”
【发布时间】:2018-02-14 04:17:22
【问题描述】:

我正在尝试将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}]>

【问题讨论】:

标签: python json django


【解决方案1】:

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

【讨论】:

  • 如果我想获取与 fk 相关的值怎么办?例如 userID__username,我将如何使用 fields=() 来做到这一点?
  • @dantheman 我正在为像我一样偶然发现此问题的任何人添加此评论。这是正确的做法:docs.djangoproject.com/en/2.2/topics/serialization/…
【解决方案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)

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 1970-01-01
    • 2012-02-22
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多