5

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

anderish
  • 1,709
  • 6
  • 25
  • 58
  • Anser here: https://stackoverflow.com/a/9061105/1571826 – Def_Os Sep 05 '17 at 19:45
  • tried it already, using `only` didn't work. – anderish Sep 05 '17 at 19:46
  • Try putting your query set (stripped down to the values dict) into a top level dictionary like {'thing': the_queryset} and serialize that object. Sometimes the serializer won't let you serialize a list-like thing because security. – theWanderer4865 Sep 05 '17 at 19:55
  • Possible duplicate of [Django - How can you include annotated results in a serialized QuerySet?](https://stackoverflow.com/questions/25401103/django-how-can-you-include-annotated-results-in-a-serialized-queryset) – Sachin Sep 05 '17 at 20:47

2 Answers2

8

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',))
wencakisa
  • 5,850
  • 2
  • 15
  • 36
  • 2
    What if I wanted to get values related to a fk? for example userID__username, how would I do this using the fields=() ? – dantheman Mar 06 '19 at 01:20
  • @dantheman I'm adding this comment for anyone who stumbles upon this issue like I did. This is the proper way to do it: https://docs.djangoproject.com/en/2.2/topics/serialization/#natural-keys – Hunter Jun 17 '19 at 14:04
6

you can try it:

import json
from django.core.serializers.json import DjangoJSONEncoder

qs = Fund.objects.values('structure').annotate(
    total=Count('structure')
).order_by('-total')
structure = json.dumps(list(qs), cls=DjangoJSONEncoder)
Brown Bear
  • 19,655
  • 10
  • 58
  • 76