MongoEngine 文档继承


可以定义任何用户定义的 Document 类的继承类。如果需要,继承的类可能会添加额外的字段。但是,由于此类不是 Document 类的直接子类,因此它不会创建新集合,而是将其对象存储在其父类使用的集合中。在父类中,元属性‘ 允许继承 在下面的例子中,我们首先将employee定义为一个文档类,并将allow_inheritance设置为true。工资类是从雇员派生的,增加了两个字段 dept 和 sal。 Employee 的对象以及薪水等级都存储在员工集合中。

在下面的示例中,我们首先将employee 定义为文档类并将allow_inheritance 设置为true。工资类是从雇员派生的,增加了两个字段 dept 和 sal。 Employee 的对象以及薪水等级都存储在员工集合中。

from mongoengine import *
con=connect('newdb')
class employee (Document):
name=StringField(required=True)
branch=StringField()
meta={'allow_inheritance':True}
class salary(employee):
dept=StringField()
sal=IntField()
e1=employee(name='Bharat', branch='Chennai').save()
s1=salary(name='Deep', branch='Hyderabad', dept='Accounts', sal=25000).save()

我们可以验证两个文档存储在员工集合中,如下所示:

{
"_id":{"$oid":"5ebc34f44baa3752530b278a"},
"_cls":"employee",
"name":"Bharat",
"branch":"Chennai"
}
{
"_id":{"$oid":"5ebc34f44baa3752530b278b"},
"_cls":"employee.salary",
"name":"Deep",
"branch":"Hyderabad",
"dept":"Accounts",
"sal":{"$numberInt":"25000"}
}

请注意,为了识别相应的 Document 类,MongoEngine 添加了一个“_cls”字段并将其值设置为“employee”和“employee.salary”。

如果你想为一组 Document 类提供额外的功能,但没有继承开销,你可以首先创建一个 abstract 类,然后从同一个类派生一个或多个类。为了使类抽象,元属性“抽象”设置为 True。

from mongoengine import *
con=connect('newdb')

class shape (Document):
    meta={'abstract':True}
    def area(self):
        pass

class rectangle(shape):
    width=IntField()
    height=IntField()
    def area(self):
        return self.width*self.height

r1=rectangle(width=20, height=30).save()