MongoEngine _types and _cls fields

落花浮王杯 提交于 2019-12-04 06:18:53
Crazyshezy

Mongoengine allows Document Inheritance. When defining a class a meta attribute allow_inheritance is used to allow subclassing this particular class. The _cls and _types fields are used to identify which class the object belongs to.

Consider a document called User used to store users' information:

class User(Document):
    meta = {'allow_inheritance': True}
    # stores information regarding a user

Now consider a document called StackOverFlowUser : this document is inherited from the User document and saves some StackOverflow-related information for a user:

class StackOverFlowUser(User):
    # stores StackOverflow information of a user

For both these document classes, mongoengine will use the same collection named user. No matter which document object you create, it will be stored as a document in this collection.

To differentiate to which class the object belongs to, _cls and _types fields will be used.

For a User object:

{
    ...
    '_cls' = 'User',
    '_types' = ['User', 'User.StackOverFlowUser']
}

For a StackOverFlowUser object:

{
    ...
    '_cls' = 'User.StackOverFlowUser',
    '_types' = ['User', 'User.StackOverFlowUser']
}

If you are sure that a document is not going to have a sub-class document, then set allow_inheritance to False and mongoengine will not save _cls and _types fields for that document.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!