Paras
Paras

Reputation: 3491

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

Upvotes: 4

Views: 1232

Answers (3)

belkka
belkka

Reputation: 273

From Django Rest Framework documentation on Serializers:

The Serializer class is itself a type of Field, and can be used to represent relationships where one object type is nested inside another.

So you can just create serializer class with fields "A" and "B" as follows:

from rest_framework import serializers

class ABSerializer(serializers.Serializer):
    A = ASerializer()
    B = BSerializer()

and use it like this:

from rest_framework.generics import RetrieveAPIView

class ABView(RetrieveAPIView):
    serializer_class = ABSerializer

    def get_object(self):
        return {'a': self.get_object_a(), 'b': self.get_object_b()}

Upvotes: 1

paras chauhan
paras chauhan

Reputation: 787

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
    })

Upvotes: 1

Saiful Azad
Saiful Azad

Reputation: 1941

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)

Upvotes: 1

Related Questions