afi
afi

Reputation: 603

How can i bind two serializers into separate one serializer django rest framework?

info: One is User and the Second one is User Data like phone number,city etc Now i can add these two serializer into third serializer and show all data in third one

Problem: now i want to create new Serializer Where i can combine both serializer attributes. but i don't understand how can i achieve to bind two serializer into different one and show all data?

serializers.py

class ContactSerializer(serializers.ModelSerializer):

    class Meta:
        model = Contact
        fields = ['email', 'phone']


class LocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Location
        fields = ['city']

Want to achieve

class CombineSerializer(serializers.ModelSerializer):

    class Meta:
        fields = ['email', 'phone', 'city']

Upvotes: 0

Views: 2717

Answers (1)

Jeet Patel
Jeet Patel

Reputation: 1241

You can simply create an object of a LocationSerializer in your contact serializer. This approach will create a nested object of location serializer.

class ContactSerializer(serializers.ModelSerializer):

    location = LocationSerializer() #if the contact serializer have multiple city then just add `many=True` as an argument.

    class Meta:
        model = Contact
        fields = ['email', 'phone', 'location']

While listing the object will look like this -

{
    'email':'[email protected]',
    'phone':'00009999888', 
    'location':{
        'city':'some_city'
    }
}

However, if you want to have both objects as a nested object than in that case you can simply call the serializer in the CombineSerializer class. But here instead of using serializers.ModelSerializer you will have to use serializers.Serializer as no model is associated with it.

This is how you can achieve it -

class CombineSerializer(serializers.Serializer):

    contact = ContactSerializer()
    location = LocationSerializer()

In this case while listing the object will look like this -

{
    'contact' : {
        'email' : '[email protected]',
        'phone' : '00999887666'
    },
    'location' : {
        'city' : 'Some City'
    }
}

Upvotes: 2

Related Questions