Gie
Gie

Reputation: 1939

Serialization to JSON two querysets in Django

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?

Upvotes: 3

Views: 5038

Answers (2)

tayfun
tayfun

Reputation: 3135

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.

Upvotes: 3

thikonom
thikonom

Reputation: 4267

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

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

Upvotes: 7

Related Questions