[Fixed]-Django REST Framework relationship serialization

1👍

You are getting Integrity error because it’s expecting the author instance but you are sending the pk related to author. Try this

serializers.py

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

    class Meta:
        model = Book
        fields = ('id','url', 'author', 'genre', 'title', 'isbn', 'summary',)

    def create(self, validated_data):
        author_id = self.initial_data.pop("author")
        genre_id = self.initial_data.pop("genre")
        author = Author.objects.get(id=author_id)
        genre = Genre.objects.get(id=genre_id)
        book = Book.objects.create(author=author, genre=genre, **validated_data)
        return book

Leave a comment