2👍
✅
You can define author_name
field with source
argument to get the name of an author.
From the DRF docs on source
argument:
The name of the attribute that will be used to populate the field. May
be a method that only takes aself
argument, such as
URLField('get_absolute_url')
, or may use dotted notation to traverse
attributes, such asEmailField(source='user.email')
.
Final Code:
class BookMetaSerializer(serializers.ModelSerializer):
# use dotted notation to traverse to 'name' attribute
author_name = serializers.CharField(source='author.name', read_only=True)
class Meta:
model = Book
fields = ('title','date','author_name',)
Source:stackexchange.com