使用django-rest-framework 3.0并具有以下简单模型:
class Book(models.Model):
title = models.CharField(max_length=50)
class Page(models.Model):
book = models.ForeignKey(Books, related_name='related_book')
text = models.CharField(max_length=500)
并给出此JSON请求:
{
"book_id":1,
"pages":[
{
"page_id":2,
"text":"loremipsum"
},
{
"page_id":4,
"text":"loremipsum"
}
]
}
如何编写嵌套的序列化程序来处理此JSON,并为page
给定的每个JSONbook
创建一个新页面或更新(如果存在)。
class RequestSerializer(serializers.Serializer):
book_id = serializers.IntegerField()
page = PageSerializer(many=True)
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
我知道用实例化序列化程序instance
会更新当前序列化程序,但是我应该如何在create
嵌套序列化程序的方法中使用它呢?
you might want to only support book updates ... , only include the update() method
。在这种情况下,instance
in更新方法将如何用现有书籍填充?