Categories
Python Answers

How to retrieve a Foreign Key value with Python django-rest-framework serializers

Spread the love

To retrieve a Foreign Key value with Python django-rest-framework serializers, we add the foreign key field into our serialize and put the field in the tuple list in the Meta class.

For instance, we write

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

to add the ItemSerializer that has the category_name field set to a CharField that has source set to the category.name column.

And then in the Meta class, we have fields set to a tuple with the category_name` field in it to return it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *