[Django]-How to get a foreignkey object to display full object in django rest framework

14👍

Use depth=1 in your Meta class of serializer,

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )
        depth = 1
👤JPG

3👍

You can create a UserSerializer and use it in ProfileSerializer like this(using as nested serializer):

class UserSerializer(serializers.ModelSerializer):
     class Meta:
         model = User
         fields = (
            'username',
            'first_name',
            # and so on..
         )

class ProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )
👤ruddra

Leave a comment