什么是在django rest文档中传递给ListSerializer中的update方法的实例参数

时间:2018-05-20 05:36:20

标签: python-3.x django-rest-framework

在django rest文档中传递给ListSerializer中的.update()方法的实例参数是什么。(link to documentation ListSerializer)。

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

1 个答案:

答案 0 :(得分:0)

如果您检查DRF的ListSerializer类的测试用例,您可以看到它要传递一个dicts列表:

价: https://github.com/encode/django-rest-framework/blob/f148e4e2593e55c76c746c85422924c33ec435cc/tests/test_serializer_lists.py#L390

相关问题