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}]>
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',))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With