user2579823
user2579823

Reputation: 411

Customizing serializers format

I'd like to customize DRF serializers so that instead of parsing / outputting say, "contact" objects like so:

{
    "name": "foo",
    "email": "[email protected]"
}

It would do wrap it inside a "contact" attribute in the JSON, e.g.

{
    "contact": {
        "name": "foo",
        "email": "[email protected]"
    }
}

Similarly, the ListSerizalizer would return a list of contacts like so:

{
    "contacts": [
       <item1>,
       <item2>...
    ]
}

Any ideas on how to go about this?

Cheers -JM

Upvotes: 0

Views: 40

Answers (2)

alex2007v
alex2007v

Reputation: 1300

You have to create two serializers one for Contact and second one for contacts. Than you have to do next:

class ContactSerializer(serializers.Serializer):
    # it should contain your fields

class AddrBook(serializers.Serializer):
    contacts = ContactSerializer(many=True)

You can find more about nested serializers there https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

Upvotes: 1

MjZac
MjZac

Reputation: 3536

You can override to_representation method to customize the serialization.

def to_representation(self, instance):
    ret = super().to_representation(instance)
    return {"contact": ret}

Documentation

Upvotes: 1

Related Questions