如何使用 Django Rest Framework 反序列化嵌套对象

mat*_*hew 5 django json django-rest-framework

假设我有这样的 Django 模型:

class Book(models.Model):
  title = models.CharField(max_length=150)
  author = models.CharField(max_length=150) 

class Chapter(models.Model):
  book = models.ForeignKey(Book, related_name='chapters')
  title = models.CharField(max_length=150)
  page_num = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)

和 Django Rest Framework 类,如下所示:

class ChapterSerializer(serializers.ModelSerializer):
  class Meta:
    model = Chapter
    fields = ('id', 'title', 'page_num')

class BookSerializer(serializers.ModelSerializer):
  chapters = ChapterSerializer(many=True)

  class Meta:
    model = Book
    fields = ('id', 'title', 'author', 'chapters')

  def create(validated_data):
    chapters = validated_data.pop('chapters')
    book = Book(**validated_data)
    book.save()
    serializer = ChapterSerializer(data=chapters, many=True)
    if serializer.is_valid(raise_exception=True):
        chapters = serializer.save()

class BookCreate(generics.CreateAPIView):
  serializer = BookSerializer(data=request.data)
  if serializer.is_valid(raise_exception=True):
    serializer.save()
  # Do some other stuff
Run Code Online (Sandbox Code Playgroud)

我发布了一些这样的 JSON:

{
  title: "Test book",
  author: "Test author",
  chapters: [
    {title: "Test chapter 1", page_num: 1},
    {title: "Test chapter 2", page_num: 5}
  ]
}
Run Code Online (Sandbox Code Playgroud)

我得到一个例外,因为chapter没有book与之关联的。如果我添加book为 的字段之一ChapterSerializer,那么 JSON 将无法验证,因为BookSerializerinBookCreate将无法验证,因为它需要章节的书 ID,但书尚未创建。我该如何解决这种情况?

有没有办法让 theBookSerializer验证它自己的字段而不是验证它的chapter's ?

Tod*_*dor 6

您可以在 上传递其他参数.save。所以我认为你只需要将新创建的书实例传递给serializer,例如

def create(validated_data):
    chapters = validated_data.pop('chapters')
    book = Book(**validated_data)
    book.save()
    serializer = ChapterSerializer(data=chapters, many=True)
    if serializer.is_valid(raise_exception=True):
        chapters = serializer.save(book=book)
Run Code Online (Sandbox Code Playgroud)

  • @trixn 关于序列化器内部的冗余验证提出了很好的观点,请检查他的答案。 (2认同)