Change a field in a Django REST Framework ModelSerializer based on the request type? : <p>Consider this case where I have a <code>Book</code> and <code>Author</code> model. </p>

<p>serializers.py</p>

<pre><code>class AuthorSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Author
        fields = ('id', 'name')

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer(read_only=True)

    class Meta:
        model = models.Book
        fields = ('id', 'title', 'author')
</code></pre>

<p>viewsets.py</p>

<pre><code>class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
</code></pre>

<p>This works great if I send a <code>GET</code> request for a book. I get an output with a nested serializer containing the book details and the nested author details, which is what I want.</p>

<p>However, when I want to create/update a book, I have to send a <code>POST</code>/<code>PUT</code>/<code>PATCH</code> with the nested details of the author instead of just their id. I want to be able to create/update a book object by specifying a author id and not the entire author object. </p>

<p>So, something where my serializer looks like this for a <code>GET</code> request</p>

<pre><code>class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer(read_only=True)

    class Meta:
        model = models.Book
        fields = ('id', 'title', 'author')
</code></pre>

<p>and my serializer looks like this for a <code>POST</code>, <code>PUT</code>, <code>PATCH</code> request</p>

<pre><code>class BookSerializer(serializers.ModelSerializer):
    author = PrimaryKeyRelatedField(queryset=Author.objects.all())

    class Meta:
        model = models.Book
        fields = ('id', 'title', 'author')
</code></pre>

<p>I also do not want to create two entirely separate serializers for each type of request. I'd like to just modify the <code>author</code> field in the <code>BookSerializer</code>. </p>

<p>Lastly, is there a better way of doing this entire thing?</p>
