Django ValueQuerySet的序列化 [英] Django Serializing of ValueQuerySet
本文介绍了Django ValueQuerySet的序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我得到了以下ValueQuerySet
So I got the following ValueQuerySet
records = Maintenance.objects.values('failure').annotate(fcount=Count('failure'))
Out[13]: <QuerySet [{'failure': 'Bend Pin', 'fcount': 2}, {'failure': 'Winding Failure', 'fcount': 2}, {'failure': 'Degraded Capacitor', 'fcount': 2}]>
我尝试使用Django的序列化器对此序列化;
I tried serializing this with Django's serializer;
from django.core import serializers
serializers.serialize('json', records, fields('failure', 'fcount'))
AttributeError: 'dict' object has no attribute '_meta'
我知道我可以使用json.dumps序列化记录,但是我想理解为什么Django的序列化器会给我这个错误.我在Python 3.8.2上运行.和Django 3.0.5.
I know I can serialize the records with json.dumps, but I want to understand why Django's serializer gives me this error. I'm running on Python 3.8.2. and Django 3.0.5.
推荐答案
来自文档
实际上,第二个参数可以是产生 Django模型实例 的任何迭代器,但几乎总是
QuerySet
.
在您的情况下, 记录
是一个可重复,但是记录的 内容
不是Django模型实例,而是 dict
对象
In your case, The records
is an iterable, but, the contents of the records
is not a Django model instance, but a dict
object
In [13]: type(records)
Out[13]: django.db.models.query.QuerySet
In [14]: type(records[0])
Out[14]: dict
这篇关于Django ValueQuerySet的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文