Clone an existing document to a new sibling class document using mongoengine

蓝咒 提交于 2019-12-23 22:14:09

问题


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!



来源:https://stackoverflow.com/questions/9776833/clone-an-existing-document-to-a-new-sibling-class-document-using-mongoengine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!