I have looked around for the past few days and couldn't find a good way to do this. I found a couple other threads but nothing seemed to work the way I needed it to.
Here is the problem: I want to be able to serialize the result of multiple queries to return to the user so they don't have to connect to the API at multiple endpoints and so the server can do all of the heavy lifting when necessary.
I'm using APIView and a get request in views.py.
I have tried using chain from itertools but I can't seem to access the data from the serializer in any way. I have tried passing in a dictionary containing the results of the two queries and that didn't seem to work either.
There is probably a really simple way of solving this but I can't seem to find any documentation on it.
This is a simplified piece of code so someone could answer easily:
views.py
class ModelOutputList(APIView):
def get(self, request):
data = self.get_queryset()
serializer = ModelOutputSerializer(
data,
many=True
)
return Response(serializer.data)
def get_queryset(self):
model1 = Model1.objects.all()
model2 = Model2.objects.all()
data = list(itertools.chain(model1, model2))
return data
serializers.py
class ModelOutputSerializer(serializers.Serializer):
model1 = Model1Serializer(many=True)
model2 = Model2Serializer(many=True)
class Meta:
fields = ('model1', 'model2')
As always, any help would be greatly appreciated.