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()