[Answered ]-Include Specific Foreign Keys in DRF Serializer

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 a self argument, such as
URLField('get_absolute_url'), or may use dotted notation to traverse
attributes
, such as EmailField(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',)

Leave a comment