1

A usual copy of a certain object of class A in Django would look like this:

obj = A.objects.get(...) # get the object
obj.id = None
obj.save()

However if class A has a foreign key of some class B than the copy will reference the same object as the initial object, which will break constraints sometimes.

How can I make django recursively duplicate all the referenced objects as well?

I suppose it would look something like this:

def duplicate(obj):
   obj.id = None
   obj.save()
   refs = ? # somehow get the inner objects which are foreign keys       
   for inner_obj in refs:
      duplucate(inner_obj)

obj = A.objects.get(...) # get the object
duplicate(obj)
Grigor Gevorgyan
  • 6,753
  • 4
  • 35
  • 64
  • this will help you https://stackoverflow.com/questions/32234986/duplicate-django-model-instance-and-all-foreign-keys-pointing-to-it – Sagar Jun 05 '17 at 16:45
  • Possible duplicate of [Duplicate Django Model Instance and All Foreign Keys Pointing to It](https://stackoverflow.com/questions/32234986/duplicate-django-model-instance-and-all-foreign-keys-pointing-to-it) – e4c5 Jun 06 '17 at 14:11

0 Answers0