Django Serializing of ValueQuerySet

匆匆过客 提交于 2021-01-05 07:04:17

问题


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}]>

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'

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.


回答1:


From the doc

Actually, the second argument can be any iterator that yields Django model instances , but it’ll almost always be a QuerySet.

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


来源:https://stackoverflow.com/questions/63701144/django-serializing-of-valuequeryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!