0

How do I clone a model in such a way that it includes (clones) data on FK-related models? I've looked through various related questions on Stack, and found most of them are for old/outdated versions of Django. Here's some illustrative model code (with str methods, etc omitted for brevity):

class Tracking(models.Model):
    entry        = models.CharField(blank=False, max_length=50)
    timestamp    = models.DateTimeField(null=True, auto_now_add=True)
    active       = models.BooleanField(default=False)

class Author(models.Model):
    entry       = models.ForeignKey(Tracking, on_delete=models.CASCADE)
    first_name  = models.CharField(blank=False, max_length=50)
    last_name   = models.ImageField(null=True, blank=True)

class Scene(models.Model):
    entry       = models.ForeignKey(Tracking, on_delete=models.CASCADE)
    location    = models.CharField(blank=False, max_length=50)
    image       = models.ImageField(null=True, blank=True)

My desired result would be to clone an existing "entry" on the Tracking model, such that a new "entry" on a new row is created with its own PK, as well as cloned copies of "Author" and "Scene" data on their respective tables which also point to the new cloned "entry". Any pointers in the right direction would be helpful. I'm not finding anything in the django docs.

Milo Persic
  • 985
  • 1
  • 7
  • 17
  • Do you want to do this for all instances or a particular one? What's wrong with getting the one that you want and creating new instances of the necessary models? – gdef_ Sep 23 '19 at 21:13
  • Thanks, I mean a particular instance. For a little background, I want my users to be able to replicate the full model and dependent models so they can edit and save them, eventually "publishing" them. The "published" records would be active=True on the Tracking model, but an admin could roll back to a previous set of data by making that record active. This is actually ambitious for my current skill level, and I'm even wondering if I'm thinking about this the right way. – Milo Persic Sep 23 '19 at 21:50

1 Answers1

0

The answer, as it turns out, is a function written by Stephen G Tuggy, as shown in this post.

I was able to modify this code for my purposes and run it successfully in the shell. It's awesome. Big thanks to Stephen for this. The "has_key()" function is deprecated and needs to be replaced with "in", as in "if field.name in" etc. Otherwise it's all good as of Python 3.7/Django 2.2.

Milo Persic
  • 985
  • 1
  • 7
  • 17