Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data of two different serializers to be passed as reference in Django Rest Framework

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

like image 409
Paras Avatar asked Sep 03 '25 03:09

Paras


2 Answers

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)
like image 136
Saiful Azad Avatar answered Sep 04 '25 23:09

Saiful Azad


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
    })
like image 20
paras chauhan Avatar answered Sep 05 '25 00:09

paras chauhan