3

To make a clone of a model in Django, I can use this trick:

object.pk=None;
object.save();

Assume I have models A, AB, and ABC. AB has a foreign key of A, ABC has a foreign key of AB.

Now if I want to make a deep clone of one A object a, I have to do it like this:

newa = deepcopy(a)
newa.pk=None
newa.save()

ab = AB.objects.get(a=a)
newab = deepcopy(ab)
newab.a = newa;
newab.pk=None
newab.save()

abc = ABC.objects.get(ab=ab)
abc.pk=None;
abc.ab=newab;
abc.save()

This is a lot of trouble if there are multiple levels of relationship. Is there a convenient way to do this, like DELETE CASCADE in sql, only for clone?

NeoWang
  • 17,361
  • 24
  • 78
  • 126
  • 4
    You need to manually copy the "related" stuff, see [docs](https://docs.djangoproject.com/en/1.4/topics/db/queries/#copying-model-instances). – alecxe May 17 '14 at 05:07
  • 1
    Possible duplicate: http://stackoverflow.com/questions/437166/duplicating-model-instances-and-their-related-objects-in-django-algorithm-for – Udi May 17 '14 at 21:45

0 Answers0