查询集序列化:AttributeError:'dict' 对象没有属性 '_meta'

and*_*ish 4 python django json

我正在尝试将 aqueryset作为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'))
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:AttributeError: 'dict' object has no attribute '_meta'这是我的查询集:<QuerySet [{'total': 106, 'structure': 'Corp'}, {'total': 43, 'structure': 'Trust'}, {'total': 2, 'structure': 'OM'}, {'total': 0, 'structure': None}]>

wen*_*isa 7

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',))
Run Code Online (Sandbox Code Playgroud)

  • 如果我想获得与 fk 相关的值怎么办?例如 userID__username,我将如何使用 fields=() 做到这一点? (2认同)

Bea*_*own 6

你可以试试看:

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)
Run Code Online (Sandbox Code Playgroud)