gpt4 book ai didi

python - 如何将不是 "Document"的直接子类的子类存储在自己的集合中?

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:20 25 4
gpt4 key购买 nike

根据 Document Inheritence 上的 MongoEngine 文档

我尝试创建一个基类,如下所示

import datetime
from mongoengine import *
connect("testdb")
class Base(Document):
companyId = StringField(required=True)
creationDate = DateTimeField()
modifiedDate = DateTimeField()

meta = {'allow_inheritance': True}

def save(self, *args, **kwargs):
if not self.creationDate:
self.creationDate = datetime.datetime.now()
self.modifiedDate = datetime.datetime.now()
return super(Base, self).save(*args, **kwargs)

class Child1(Base):
# identifier = StringField(required=True, unique=True, primary_key=True)
createdBy = StringField(required=True)

class Child2(Base):
memberId = StringField(required=True)

Child1(companyId='ab', createdBy='123').save()
Child2(companyId='ab', memberId='123').save()

我的目标是在“testdb”下创建两个名为 Child1 和 Child2 的集合,但只创建一个名为“base”的集合,其中包含两个文档。

{
"_id" : ObjectId("5656b66381f49543f27af85a"),
"_cls" : "Base.Child1",
"companyId" : "ab",
"creationDate" : ISODate("2015-11-26T13:06:01.689Z"),
"modifiedDate" : ISODate("2015-11-26T13:06:01.689Z"),
"createdBy" : "123"
}

/* 1 */
{
"_id" : ObjectId("5656b66381f49543f27af85b"),
"_cls" : "Base.Child2",
"companyId" : "ab",
"creationDate" : ISODate("2015-11-26T13:06:03.621Z"),
"modifiedDate" : ISODate("2015-11-26T13:06:03.621Z"),
"memberId" : "123"
}

如何为我的子类指定不同的集合名称?

版本

python 2.7.10

mongodb 3.0.3

mongoengine 0.8.7

pymongo 2.7.2

最佳答案

这是根据 documentation 的预期行为你链接。

To create a specialised type of a Document you have defined, you may subclass it and add any extra fields or methods you may need. As this is new class is not a direct subclass of Document, it will not be stored in its own collection; it will use the same collection as its superclass uses.

据说要存储在它自己的集合中,您需要基类必须是抽象类,并且您可以选择使用其元属性指定子类集合的名称。

class Base(Document):
...
meta = {
'allow_inheritance': True,
'abstract': True
}
...

class Child1(Base):
...
meta = {'collection': 'child1'} # optional

关于python - 如何将不是 "Document"的直接子类的子类存储在自己的集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33933152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com