Retrieving a Foreign Key value with django-rest-framework serializers
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
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')
Another thing you can do is to:
- create a property in your
Item
model that returns the category name and - expose it as a
ReadOnlyField
.
Your model would look like this.
class Item(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, related_name='items') def __unicode__(self): return self.name @property def category_name(self): return self.category.name
Your serializer would look like this. Note that the serializer will automatically get the value of the category_name
model property by naming the field with the same name.
class ItemSerializer(serializers.ModelSerializer): category_name = serializers.ReadOnlyField() class Meta: model = Item