MrK*_*tts 5 python django django-models python-3.x
使用Django 1.9 和 Python 3.4,我想复制现有模型实例及其所有相关数据。以下是我目前如何实现这一目标的示例。我的问题是,有没有更好的方法?
我已经阅读了一些帖子,例如在 Django / Algorithm 中复制模型实例及其相关对象,用于重复复制一个对象,但是,它们已经超过 8 年了,不再与 Django 1.9+ 一起使用。
下面是我如何尝试在 Django 1.9 中实现这一点,好的还是更好的方法?
楷模
class Book(models.Model):
name = models.CharField(max_length=80)
class Contributor(models.Model):
name = models.CharField(max_length=80)
books = models.ForeignKey("Book", related_name="contributors")
Run Code Online (Sandbox Code Playgroud)
复制功能。我必须在保存新的 Book 实例后重新创建贡献者,否则,它将从我正在复制的实例中分配现有的贡献者。
def copy_book(self, id):
view = self.context['view']
book_id = id
book = Book.objects.get(pk=book_id)
copy_book_contributors = book.contributors.all()
book.id = None
# make a copy of the contributors items.
book.save()
for item in copy_book_contributors:
# We need to copy/save the item as it will reassign the existing one.
item.id = None
item.save()
book.contributors.add(item)
Run Code Online (Sandbox Code Playgroud)
对于这种特殊的情况下,你可以bulk_create在contributors:
contributor_names = list(book.contributors.values_list('name', flat=True))
book.id = None
book.save()
# create the contributor object with the name and new book id.
contributors = [Contributor(name=name, book_id=book.id) for name in contributor_names]
Contributor.objects.bulk_create(contributors)
Run Code Online (Sandbox Code Playgroud)