Django REST Framework - Nested Serializers


DRF tip:

To easily join parent and child objects inside a single response body, you can use a nested serializer.

👇

# serializers:
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ("title", "content")


class TagSerializer(serializers.ModelSerializer):
    posts = PostSerializer(many=True, read_only=True)

    class Meta:
        model = Tag
        fields = ['name', 'posts']

# result:
{
    "name": "Stories",
    "posts": [
        {
            "title": "My first story",
            "content": "She opened the door and..."
        },
        {
            "title": "Story about a dog",
            "content": "I met Chase when I was..."
        }
    ]
}

For more, review Nested Serializers.