title: Duplicate Django Model Instance and All Foreign Keys Pointing to It
body: <p>I want to create a method on a Django model, call it <code>model.duplicate()</code>, that duplicates the model instance, including all the foreign keys pointing to it. I know that you can do this:</p>
  
  <pre><code>def duplicate(self):
     self.pk = None
     self.save()
  </code></pre>
  
  <p>...but this way all the related models still point to the old instance.</p>
  
  <p>I can't simply save a reference to the original object because what <code>self</code> points to changes during execution of the method:</p>
  
  <pre><code>def duplicate(self):
      original = self
      self.pk = None
      self.save()
      assert original is not self    # fails
  </code></pre>
  
  <p>I could try to save a reference to just the related object:</p>
  
  <pre><code>def duplicate(self):
      original_fkeys = self.fkeys.all()
      self.pk = None
      self.save()
      self.fkeys.add(*original_fkeys)
  </code></pre>
  
  <p>...but this transfers them from the original record to the new one. I need them copied over and pointed at the new record.</p>
  
  <p>Several answers elsewhere (and here before I updated the question) have suggested using Python's <a href="https://docs.python.org/2/library/copy.html" rel="noreferrer"><code>copy</code></a>, which I suspect works for foreign keys <em>on this model</em>, but not foreign keys on another model pointing to it.</p>
  
  <pre><code>def duplicate(self):
      new_model = copy.deepcopy(self)
      new_model.pk = None
      new_model.save()
  </code></pre>
  
  <p>If you do this <code>new_model.fkeys.all()</code> (to follow my naming scheme thus far) will be empty.</p>