【发布时间】:2014-09-26 22:29:23
【问题描述】:
我正在寻找最快、最简单的方法来复制模型实例和相关模型。我发现了一些技术 here 和 here 但我认为它们是基于旧的 django 版本。
我已经通过循环实现了它,但是有没有更好的方法呢?我尝试了django-forkit plugin,但遇到了problem with model that have a foreignkey field with auth.User.
型号:
class Book(Folder):
filename = models.CharField(max_length=255)
created_by = models.ForeignKey(User)
class Chapter(models.Model):
book = models.ForeignKey(Book)
name = models.CharField(max_length=255, db_index=True)
class Page(models.Model):
book = models.ForeignKey(Book)
attribute_value = hstore.DictionaryField(db_index=True)
重复功能:
book = Book.objects.get(pk=node_id, created_by=request.user)
chapters = Chapter.objects.filter(book=book)
pages = Page.objects.filter(book=book)
book.pk = None
book.id = None
book.filename = book.filename + "_copy"
book.save()
for chapter in chapters:
chapter.book= book
chapter.pk = None
chapter.save()
for page in pages:
page.book= book
page.pk = None
page.save()
【问题讨论】:
-
鉴于您的模型简单,我会坚持使用您的解决方案,但如果您正在寻找更通用的方法,请查看
NestedObjects类:stackoverflow.com/questions/12158714/… -
@Germano,感谢您的链接。我想知道你是如何在 final 复制所有嵌套对象的。
-
您好,我觉得这个解决方案没问题;您还可以查看 ORM 的
bulk_create方法,看看是否可以在不多次访问数据库的情况下保存章节和页面。 docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create。 (也就是说,如果在 Chapter.save() 和 Page.save() 中当然没有发生奇怪的工作人员)