I am using the Django Rest Framework in an API project and trying to figure out if there is a way to use two different serializers with common views (e.g. CreateAPIView). I want to use one serializer to deserialize a POST request and another to serialize the received response.
Here is what I am trying to do; I will illustrate the use of album / track examples from documents:
The model I'm working with has a ForeignKey relationship. In the API, I would just like to include FK in the request when assigning the relationship, so in the serializer I use PrimaryKeyRelatedField, just like the AlbumSerializer processes the relation to the tracks:
class CreateAlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks')
However, in response, I would like to include a full view of the album using ModelSerializer, not just PK, slug, etc., something like this:
class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') class TrackSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ('order', 'title', 'duration')
General DRF views allow you to either specify serializer_class or override the get_serializer_class method, but I cannot figure out how to use this to accomplish what I need.
Is there something obvious that I'm missing? It seems like a reasonable thing to do, but I can't figure out how to do it.