【问题标题】:Django Rest Framework ListSerializer Partial UpdateDjango Rest Framework ListSerializer 部分更新
【发布时间】:2020-04-12 22:29:32
【问题描述】:

我正在编写一个序列化程序来为 django 模型提供多个部分更新。我正在遵循 DRF api 指南中出现的示例实现,在下面复制并在此处链接:https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update

从 django-rest-framework 文档中检索到以下内容:

serializer.py

class BookListSerializer(serializers.ListSerializer):
    def update(self, instance, validated_data):
        # Maps for id->instance and id->data item.
        book_mapping = {book.id: book for book in instance}
        data_mapping = {item['id']: item for item in validated_data}

        # Perform creations and updates.
        ret = []
        for book_id, data in data_mapping.items():
            book = book_mapping.get(book_id, None)
            if book is None:
                ret.append(self.child.create(data))
            else:
                ret.append(self.child.update(book, data))

        # Perform deletions.
        for book_id, book in book_mapping.items():
            if book_id not in data_mapping:
                book.delete()

        return ret

class BookSerializer(serializers.Serializer):
    # We need to identify elements in the list using their primary key,
    # so use a writable field here, rather than the default which would be read-only.
    id = serializers.IntegerField()
    ...

    class Meta:
        list_serializer_class = BookListSerializer

在我的代码中,当在返回的序列化程序上调用 .save() 时,我的 views.py 中会出现 NotImplementedError('update() 必须实现。')

我的理解是 ListsSerializer 会覆盖 .update(),所以任何人都可以帮助解释我为什么会收到 NotImpletmentedError 吗?

views.py

elif request.method == 'PATCH':
        data = JSONParser().parse(request)
        books = Book.objects.all()
        # both partial and many set to True
        serializer = BookSerializer(books, data=data, partial=True, many=True)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

【问题讨论】:

  • 嗨,LoadingPatchSerializer 是引发错误的那个吗?你能展示一下它的实现吗?
  • @luistm,抱歉,应该是 BookSerializer。我已经编辑过了。错误来自 serializer.save()。
  • 你需要重写 BookSerializer 上的方法
  • @luistm,啊!那行得通。感谢您的帮助。
  • 这个解决方案对我不起作用。我找到了另一种使它起作用的方法,请在此处查看我的答案:stackoverflow.com/a/59756993/7392069

标签: python django django-rest-framework


【解决方案1】:

在@luistm 的帮助下,我设法解决了这个问题。继续上面的 DRF 示例,我在 bookSerializer 类中的 update() 覆盖实现如下。

serializer.py

class BookSerializer(serializers.Serializer):
    # We need to identify elements in the list using their primary key,
    # so use a writable field here, rather than the default which would be read-only.
    id = serializers.IntegerField()
    ...

    class Meta:
        list_serializer_class = BookListSerializer

    def update(self, instance, validated_data):
         """update the page number of the book and save"""
         instance.page = validated_data.get('page', instance.page)
         instance.save()
         return instance

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 2017-04-14
    • 2018-02-05
    • 2020-01-27
    • 2017-08-15
    • 2015-09-19
    • 2016-01-09
    • 2016-09-25
    • 2018-05-04
    相关资源
    最近更新 更多