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}]>
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)
你可以试试看:
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)
| 归档时间: |
|
| 查看次数: |
11682 次 |
| 最近记录: |