[Django]-Serialization to JSON two querysets in Django

7👍

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

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

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.

👤tayfun

Leave a comment