Home > OS >  Django | Serializer for Foreign Key
Django | Serializer for Foreign Key

Time:05-27

I got two models Book and Author implemented like this:

class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    name = models.CharField(max_length=50)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

In addition to this I got the following Serializers:

class AuthorSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=50)

class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=50)
    author = AuthorSerializer()

Serializing objects works without any problems.

Now I got the following situation:

Author's:

id name
1 Josh Robert
2 J. R. R. Tolkien
3 Mike Towers

I get a POST request to an API endpoint on my server

http://127.0..0.1:8000/api/book

looking like this:

payload = {
'name': 'Lord of the rings',
'author': 2
}

How can I use my Serializers to create a new Book with the given name and link it with the author no. 2?

CodePudding user response:

You can add the user_id field for writing in the BookSerializer. You don't need to set the id field by the way. Django will automatically deal with the id field if you derive from the serializers.ModelSerializer.

class AuthorSerializer(serializers.ModelSerializer):
    name = serializers.CharField(max_length=50)

    class Meta:
        fields = '__all__'
        Model = Author

class BookSerializer(serializers.ModelSerializer):
    author_id = serializers.IntegerField(write_only=True)
    name = serializers.CharField(max_length=50)
    author = AuthorSerializer(read_only = True)

    class Meta:
        fields = ('id', 'name', 'author', 'author_id',)
        Model = Book

And in frontend, payload should be

{
    'name': 'Lord of the rings',
    'author_id': 2
}
  • Related