Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate django objects with ManyToManyFields

I use Django and I have some objects with ManyToManyFields. I'd like to duplicate these objects. I've found 'deepcopy' which works almost perfectly.

>>> e = Equipement.objects.get(pk=568)
>>> ee = deepcopy(e)
>>> ee.connexion.all()
[<Connexion: COMETE - Proxyweb>]
>>> ee.id=None
>>> ee.save()
>>> ee.connexion.all()
[]

I don't want to loose the ManyToMany information when I save. Do you know a trick in order to do that quickly in Django ?

Thanks.

like image 810
psychoze Avatar asked Jun 14 '11 16:06

psychoze


1 Answers

Just add them using the old object:

ee = deepcopy(e)
ee.id=None
ee.save()
ee.connexion.add(*e.connexion.all())
like image 182
zeekay Avatar answered Sep 21 '22 22:09

zeekay