姜戈 |外键序列化器

Django | Serializer for Foreign Key

我有两个模型BookAuthor 像这样实现:

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)

除此之外,我还有以下序列化程序:

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()

序列化对象没有任何问题。

现在我得到以下情况:

作者:

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

我收到一个 POST 请求到我服务器上的 API 端点

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

看起来像这样:

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

我如何使用我的序列化程序创建具有给定名称的新书,link 作者编号。 2?

您可以在BookSerializer中添加user_id字段进行书写。 顺便说一句,您不需要设置 id 字段。如果您从 serializers.ModelSerializer.

派生,Django 将自动处理 id 字段
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

在前端,负载应该是

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