如何复制Django模型实例和所有相关数据

时间:2017-01-13 14:41:40

标签: python django python-3.x django-models

使用 Django 1.9和Python 3.4 我想复制现有模型实例及其所有相关数据。下面是我目前如何实现这一目标的一个例子。我的问题是,有更好的方法吗?

我已阅读过帖子,例如Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object这个,但是,他们超过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")

复制功能。我必须在保存新的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)

1 个答案:

答案 0 :(得分:4)

对于这种特殊情况,您可以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)