[Fixed]-How to get foreignkey field name instead of id in django rest framework

25πŸ‘

βœ…

Since you’d defined the __str__() method in your Company model, you can use the StringRelatedField() as

class UserSerializer(serializers.ModelSerializer):
    company_name = serializers.StringRelatedField()
    class Meta:
        model = User
        fields = '__all__'

UPDATE
override the to_representation method

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def to_representation(self, instance):
        rep = super(UserSerializer, self).to_representation(instance)
        rep['company_name'] = instance.company_name.name
        return rep
πŸ‘€JPG

10πŸ‘

simple solution is use source

class UserSerializer(serializers.ModelSerializer):
    company_name = serializers.CharField(source='company_name.name')
πŸ‘€Brown Bear

4πŸ‘

Use depth.

class PhoneSerializer(serializers.ModelSerializer):
    class Meta:
        model = Phone
        depth = 1
        fields = '__all__'

3πŸ‘

class UserSerializer(serializers.ModelSerializer):
    company_name = serializers.SerializerMethodField(source='get_company_name')
    class Meta:
        model = User
        fields = '__all__'
    def get_company_name(self, obj):
        return obj.company_name.name
πŸ‘€Exprator

1πŸ‘

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def to_representation(self, instance):
        rep = super(UserSerializer, self).to_representation(instance)
        rep['company_name'] = instance.company_name.name
        return rep

0πŸ‘

Here is the documentation:

This worked for me:

company_name = serializers.SlugRelatedField(read_only=True, slug_field='name')
πŸ‘€Dragos Neata

Leave a comment