I was searching for the fastest and simplest way to duplicate a model instance and related model. I found some techniques here and here but I think they are based on old django versions.
I have achieved it with loops, but is there any better way to do it? I tryed the django-forkit plugin but encounter a problem with model that have a foreignkey field with auth.User.
Models:
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)
Duplicate function:
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()
NestedObjectsclass: stackoverflow.com/questions/12158714/…bulk_createmethod and see if you can save chapters and pages without hitting the db multiple times. docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create. (That is if no weird staff is happening in Chapter.save() and Page.save() ofcourse)