[Django]-How can I include related fields to the model serialization in django rest framework?

7👍

✅

The solution is to define UserSerializer extending ModelSerializer like that

from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):

    class Meta:
        model = UserModel
        fields = ['id', 'username']

and then use it in PostSerializer:

from myapp import UserSerializer
from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
    owner = UserSerializer()

    class Meta:
        model = PostModel
        fields = ['id', 'owner']

2👍

Use the depth option within your ModelSerializer‘s Meta class:

class PostSerializer(ModelSerializer):

    class Meta:
        model = Post
        fields = ['text', 'owner']
        depth = 1

Also note that you don’t need to include the Author field.

Docs here.

Leave a comment