3

I have two models:

class User(models.Model):
  username = models.CharField()

and

class Post(models.Model):
  text = models.TextField()
  owner = models.ForeignKey(User)

Using such serializer:

from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
    owner = serializers.Field(source='owner.id')

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

I get all posts with owners' ids. How can I modify serializer to get all posts with owner fialed containing the whole user model?

I tryied from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
    owner = serializers.Field(source='owner')

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

but that only replaced id with username, not the whole model as I expected(because User's representation returns username field).

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

And about the solution. This is not exactly what I want. I want to expand the only field, not all fields to the given depth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.