问题
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