使用mongoengine将现有文档克隆到新的同级类文档 [英] Clone an existing document to a new sibling class document using mongoengine

查看:68
本文介绍了使用mongoengine将现有文档克隆到新的同级类文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

class ParentDocument(Document):
    .
    .
    .

class Child1Document(ParentDocument):
    .
    .
    .

class Child2Document(ParentDocument):

    .
    .
    .

现在让我们说我有一个类型为Child1Document的文档.是否可以将其克隆到Child2Document类型的新文档中?

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?

我试图做:

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

doc2 = Child2Document()
doc2 = doc1

但是将doc2转换为Child1Document类型.有没有一种方法可以将doc1的所有内容复制到doc2,而无需转换doc2?

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

推荐答案

是可以的,但是您需要使用Deepcopy

Yes it is possible, but you need to use deepcopy

您的代码应如下所示:

from copy import deepcopy

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

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

克隆!

这篇关于使用mongoengine将现有文档克隆到新的同级类文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆