Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest ModelSerializer select fields to display in nested relationship

I'm going to reference the django-rest-framework API example on this. Lets say we have two serializers defined as below.

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

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

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

Now if i do a GET request and retrieve an Album instance, it will return me a response with a list of Track instances inside it where each instance contains all the fields of Track. Is there a way to return only a selected subset of the fields in the Track model? For example to only return the title and duration field to the client but not the 'order' field.

like image 703
Mohammad hp Avatar asked Jan 23 '26 20:01

Mohammad hp


1 Answers

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.

like image 80
Willem Van Onsem Avatar answered Jan 25 '26 19:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!