Search code examples
pythondjangoduplicatesmanytomanyfield

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.


Solution

  • Just add them using the old object:

    ee = deepcopy(e)
    ee.id=None
    ee.save()
    ee.connexion.add(*e.connexion.all())