I’ve models for Books, Chapters and Pages. They are all written by a User:
from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter)
What I’d like to do is duplicate an existing Book and update it’s User to someone else. The wrinkle is I would also like to duplicate all related model instances to the Book – all it’s Chapters and Pages as well!
Things get really tricky when look at a Page – not only will the new Pages need to have their author field updated but they will also need to point to the new Chapter objects!
Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?
Cheers,
John
Update:
The classes given above are just an example to illustrate the problem I’m having!
This no longer works in Django 1.3 as CollectedObjects was removed. See changeset 14507
I posted my solution on Django Snippets. It’s based heavily on the
django.db.models.query.CollectedObjectcode used for deleting objects:For django >= 2 there should be some minimal changes. so the output will be like this: