Nested Response Django-Rest-Framework

Here is code snippet to render nested json response in Django Rest Framework in many to many relationship.

These is my model with many to many relationship.

class Person(models.Model):
    name = models.CharField(max_length=255)
    age = models.PositiveIntegerField()

    def __unicode__(self):
        return self.name

class PersonGroup(models.Model):
    name = models.CharField(max_length=255)
    persons = models.ManyToManyField(Person)

    def __unicode__(self):
        return self.name

These is my serializer with model serializer.

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person

class PersonGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = PersonGroup

By default many to many field in DRF will rendered as list of primary key.

persons = [
    21,
    8,
    19
]

If we need our many to many field rendered as javascript object we can use existing serializer class that we defined before as the serializer field for many to many relationship.

class PersonGroupSerializer(serializers.ModelSerializer):
    persons = PersonSerializer(many=True, read_only=True)    

    class Meta:
        model = PersonGroup

Serializer above will rendered many to many field as javascript object.

persons = [
    {"id": 21, "name": "Ari", "age": 22},
    {"id": 8, "name": "Budi", "age": 28},
    {"id": 19, "name": "Ana", "age": 42}
]

Reference: http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s