Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve foreign key field in Django rest framework?

Given the model and serializer classes below, when I retrieve Track details, it'll only show the Track title but not the related Artist.

How would I also show the Artist name when retrieving Track details?

models.py

class Artist (models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Track (models.Model):    
    artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist")
    title = models.CharField(max_length=100, verbose_name="Title")

    def __str__(self):
        return self.title

serializers.py

class ArtistSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField()

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

class TrackSerializer(serializers.ModelSerializer):

    class Meta:
        model = Track
        fields = '__all__'
like image 298
bayman Avatar asked Jun 01 '17 07:06

bayman


2 Answers

In the current version of DRF you can simply do this

class TrackSerializer(serializers.ModelSerializer):
    
    artist = serializers.StringRelatedField()

    class Meta:
        model = Track
        fields = '__all__'

StringRelatedField may be used to represent the target of the relationship using its __str__ method.

REF

like image 85
Dr Manhattan Avatar answered Oct 24 '22 15:10

Dr Manhattan


I think you need custom field, try this serializer:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('title', 'artist','artist_name')

    artist_name = serializers.SerializerMethodField('get_artists_name')

    def get_artists_name(self, obj):
        return obj.artist.name

It produce something like this.

[
    {
        "title": "Don't let me down",
        "artist": 2,
        "artist_name": "The Beatles"
    },
    {
        "title": "Summertime",
        "artist": 1,
        "artist_name": "Ella Fitzgerald"
    }
]
like image 42
Sergey M. Avatar answered Oct 24 '22 17:10

Sergey M.