MongoEngine - 文件繼承



可以定義任何使用者定義的 Document 類的繼承類。如果需要,繼承類可以新增額外的欄位。但是,由於這樣的類不是 Document 類的直接子類,因此它不會建立新的集合,而是其物件儲存在其父類使用的集合中。在父類中,元屬性“allow_inheritance 在下面的示例中,我們首先將 employee 定義為文件類並將 allow_inheritance 設定為 true。salary 類派生自 employee,並添加了兩個新的欄位 dept 和 sal。Employee 和 salary 類的物件都儲存在 employee 集合中。

在下面的示例中,我們首先將 employee 定義為文件類並將 allow_inheritance 設定為 true。salary 類派生自 employee,並添加了兩個新的欄位 dept 和 sal。Employee 和 salary 類的物件都儲存在 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()

我們可以透過以下方式驗證兩個文件是否儲存在 employee 集合中:

{
"_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()
廣告

© . All rights reserved.