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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With