Retrieving a Foreign Key value with django-rest-framework serializers
Just use a related field without setting many=True
.
Note that also because you want the output named category_name
, but the actual field is category
, you need to use the source
argument on the serializer field.
The following should give you the output you need...
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.RelatedField(source='category', read_only=True)
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
In the DRF version 3.6.3 this worked for me
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.CharField(source='category.name')
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
More info can be found here: Serializer Fields core arguments