[Django]-Django-rest ModelSerializer select fields to display in nested relationship

6👍

You can make a specific TrackSerializer for your Album, like:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class TrackForAlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackForAlbumSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']

You do not have to define a single serializer per model, you can define multiple serializers you each use for a dedicated task.

Leave a comment