3

I've some problem with JSON serialization two objects of type queryset in my Django project. For example I have:

collectionA = A.objects.all()
collectionB = B.objects.all()

When I try ot serialize only one collection:

json = serializers.serialize('json', collectionA)

then everything works properly, but how can I serialize these two collections to one json object?

Gie
  • 1,907
  • 2
  • 24
  • 49

2 Answers2

7
from itertools import chain
combined = list(chain(collectionA, collectionB))

json = serializers.serialize('json', combined)
thikonom
  • 4,219
  • 3
  • 26
  • 30
  • better than my answer, itertools.chain makes sure iterator is returned, collections are not actually combined to make one big list. – tayfun Sep 20 '12 at 10:25
  • Thanks a lot for this advice. I've one more question. How can I combine to one list 2 collection and for example int variable? – Gie Sep 20 '12 at 11:01
  • chain can be used only on iterables. So just do chain(collectionA, collectionB, [int]) but then you cannot serialize it to json, since serializers.serialize can only be used on querysets. – thikonom Sep 20 '12 at 11:02
  • OK, I understand. So what is the best approach to serialize few collections and not iterable elements for AJAX request? – Gie Sep 20 '12 at 11:13
  • 2
    Have a look at the first answer of this question: http://stackoverflow.com/questions/10502135/django-queryset-to-dict-for-use-in-json – thikonom Sep 20 '12 at 11:14
3

You cannot combine two querysets to serialize them. If you serialize one queryset, it is actually executed and the queryset data is filled in at that moment. If you only want the data in collection, just get the sets, join them and then serialize the joined collection. Something of the form:

from django.core import serializers

collectionA = list(A.objects.all())
collectionB = list(B.objects.all())
joined_collection = collectionA + collectionB
json = serializers.serialize('json', joined_collection)

Try it, this should work.

Elias Prado
  • 1,518
  • 2
  • 17
  • 32
tayfun
  • 3,065
  • 1
  • 19
  • 23
  • For readers, do not confuse this serializers with drf serializers. the import is `from django.core import serializers`. – Elias Prado Oct 21 '21 at 16:04