I have two models A and B which are not related to each other. I want to serialize those two models and send them as one JSON object, supposedly as below:
{
'A': {},
'B': {}
}
I have separate serializers for both A and B
Please have a look. I am overriding get method. Here a_obj, b_obj are the python object maybe is obtained from database.
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.response import Response
class TwoSerializedModelAPIView(RetrieveAPIView):
def get(self, request, *args, **kwargs):
a_obj = A.objects.get(id=1)
b_obj = B.objects.get(id=1)
data = {'A': ASerializer(a_obj).data, 'B': BSerializer(b_obj).data}
return Response(data=data)
You can use DjangoMultiModelApi libraray, in this library you can combine multiple model data with pagination.
and second solution is :
def get(self, request, *args, **kwargs):
a_serialzer_data = serializer_classA(query_setA, many=True)
b_serialzer_data = serializer_classB(query_setB, many=True)
return Response({
"A": a_serialzer_data.data,
"B": b_serialzer_data.data
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With