-->

Clone an existing document to a new sibling class

2019-07-03 04:18发布

问题:

I have the following classes

class ParentDocument(Document):
    .
    .
    .

class Child1Document(ParentDocument):
    .
    .
    .

class Child2Document(ParentDocument):

    .
    .
    .

Now let's say that I have a document of type Child1Document. Is it possible to clone it to a new document of type Child2Document?

I have tried to do:

doc1 = Child1Document()
doc1.attr1 = foo
doc1.save()

doc2 = Child2Document()
doc2 = doc1

but this converts doc2 to a Child1Document type. Is there a way to copy all the contents of doc1 to doc2 without converting doc2?

回答1:

Yes it is possible, but you need to use deepcopy

You code would look something like this:

from copy import deepcopy

doc1 = Child1Document()
doc1.attr1 = foo
doc1.save()

doc2 = deepcopy(doc1)
doc2.id = None
doc2.save()

Cloned!



标签: mongoengine