Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queryset Serialize: AttributeError: 'dict' object has no attribute '_meta'

I am trying to pass a queryset as a JSON object:

structure=Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total') However, querysets aren't Json Serializable therefore, I modified my code:

from django.core import serializers


structure=serializers.serialize('json',Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total'))

But I get this error: AttributeError: 'dict' object has no attribute '_meta' and this is my queryset: <QuerySet [{'total': 106, 'structure': 'Corp'}, {'total': 43, 'structure': 'Trust'}, {'total': 2, 'structure': 'OM'}, {'total': 0, 'structure': None}]>

like image 479
anderish Avatar asked Dec 14 '22 21:12

anderish


1 Answers

Django core serializers can only serialize a queryset. But values() doesn't return queryset, rather a ValuesQuerySet object. You can specifiy the fields you wish to use in values() in the serialize() method as follows:

from django.core import serializers

funds = Fund.objects.all().annotate(total=Count('structure')).order_by('-total')
structure = serializers.serialize('json', funds, fields=('structure',))
like image 64
wencakisa Avatar answered Dec 16 '22 11:12

wencakisa