'Retrieving selected fields from a Foreign Key value with django-rest-framework serializers. (how to get some of the fields of the ForeignKey.)

My Model Class for the artist, album, and track.

 
    class Artist(models.Model):
        first_name = models.CharField(max_length=100)
        last_name = models.CharField(max_length=100)
        email = models.EmailField()
    
    
    class Album(models.Model):
        album_name = models.CharField(max_length=100)
        artist = models.ForeignKey(Artist, related_name='albums', on_delete=models.CASCADE)
    
    
    class Track(models.Model):
        album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
        title = models.CharField(max_length=100)
        duration = models.IntegerField()

My serializer for the respective models.

    class ArtistSerializer(serializers.ModelSerializer):
        class Meta:
            model = Artist
            fields = '__all__'
    
    
    class TrackSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Track
            fields = ['title', 'duration']
    
   
    class AlbumSerializer(serializers.ModelSerializer):
        tracks = TrackSerializer(many=True, read_only=True)
    
        class Meta:
            model = Album
            fields = '__all__'
            depth = 1

For retrieve, The output is as

    {'id': 1, 
     'tracks': [{'title': 'Public Service Announcement', 'duration': 245}, 
                 {'title': 'What More Can I Say', 'duration': 264}], 
     'album_name': 'The Grey Album', 
      'artist': {'id': 1, 'first_name': 'lala', 'last_name': 
                'nakara','email':'[email protected]'}
     }
    

My desired output: I want to get rid of the email field. I looked at the Django-rest-framework documentation, but could not find anything related to the selective field from foreign keys.

    {'id': 1, 
     'tracks': [{'title': 'Public Service Announcement', 'duration': 245}, 
                 {'title': 'What More Can I Say', 'duration': 264}], 
     'album_name': 'The Grey Album', 
      'artist': {'id': 1, 'first_name': 'lala', 'last_name': 
                'nakara'}
     }


Solution 1:[1]

Create new artist serillizer and exclude email field.

    class ArtistWithNoEmailSerializer(serializers.ModelSerializer):
        class Meta:
            model = Artist
            exclude = ['email']


    class AlbumSerializer(serializers.ModelSerializer):
        tracks = TrackSerializer(many=True, read_only=True)
        artist = ArtistWithNoEmailSerializer()
        class Meta:
            model = Album
            fields = ['id', 'tracks', 'artist', 'album_name']


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad sadegh borouny