Django Rest Framework提供了有关如何实现批量更新的示例。 该示例显示更新方法处理更新,创建和销毁实例。 我无法理解的是新数据如何具有'id',因为我认为一旦将对象保存到数据库就会创建id / pk。根据我的理解,当新实例在validated_data中时,第二行应该失败,因为它们没有id。
示例
class BookListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
book_mapping = {book.id: book for book in instance}
data_mapping = {item['id']: item for item in validated_data} # --> shouldn't this fail if new items are 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
答案 0 :(得分:1)
我认为该示例需要设置id
。您需要一个不同的算法来处理没有id