- MongoEngine 教程
- MongoEngine - 首頁
- MongoEngine - MongoDB
- MongoEngine - MongoDB Compass
- MongoEngine - 物件文件對映器
- MongoEngine - 安裝
- MongoEngine - 連線到 MongoDB 資料庫
- MongoEngine - 文件類
- MongoEngine - 動態模式
- MongoEngine - 欄位
- MongoEngine - 新增/刪除文件
- MongoEngine - 查詢資料庫
- MongoEngine - 過濾器
- MongoEngine - 查詢運算子
- MongoEngine - QuerySet 方法
- MongoEngine - 排序
- MongoEngine - 自定義 QuerySet
- MongoEngine - 索引
- MongoEngine - 聚合
- MongoEngine - 高階查詢
- MongoEngine - 文件繼承
- MongoEngine - 原子更新
- MongoEngine - Javascript
- MongoEngine - GridFS
- MongoEngine - 訊號
- MongoEngine - 文字搜尋
- MongoEngine - 擴充套件
- MongoEngine 有用資源
- MongoEngine - 快速指南
- MongoEngine - 有用資源
- MongoEngine - 討論
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()
廣告