【问题标题】:How to copy a Django Model Instance and all related data如何复制 Django 模型实例和所有相关数据
【发布时间】:2023-03-24 13:46:01
【问题描述】:

使用 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)

【问题讨论】:

  • Book 与 Contributor 有什么关系?
  • @AKS 一本书可以有很多贡献者,我上面例子中的错字,我已经更正了,抱歉。

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


【解决方案1】:

对于这种特殊情况,您可以bulk_createcontributors

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)

【讨论】:

  • 裤子,我忘了'bulk_create'函数!列表推导的使用使它如此整洁。谢谢好答案!
  • 我会接受答案,谢谢。我能看到的唯一潜在问题是,如果稍后我将 FK 添加到贡献者模型中,我不确定 flat=True 在这种情况下是否有效,也许我可以使用值来代替。但是,这回答了我最初的问题。谢谢。
  • 这就是我提到for this particular case的原因。如果您添加额外的 pk,那么您可以使用 values 并将其转换为 dict 并将其传递给 Contributor 构造函数。那也行..
猜你喜欢
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2018-07-30
  • 2018-03-21
  • 2019-08-01
  • 2011-01-29
  • 2020-12-25
相关资源
最近更新 更多