MongoEngine _types和_cls字段 [英] MongoEngine _types and _cls fields

查看:111
本文介绍了MongoEngine _types和_cls字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么mongoengine会向集合的每个文档添加 _types _cls 字段。

这两个都是一个(键,值)对并且它们都包含文档的模型类的名称。唯一的区别是 _types value是一个列表,我假设如果涉及到一些继承,它可以有多个模型类名。

Why does mongoengine add _types and _cls fields to every document of a collection.
Both of them are a (key, value) pair and both of them contain the name of the document's model class. The only difference is _types value is a list and I assume it can have multiple model class names if there is involved some inheritance.

但是问题是:为什么我需要它们存在于集合中的每个文档中,当所有文档的两个字段都具有相同的值时?

However the question is: why do I need them to exist in every document within a collection when all the documents will have the same values for both fields?

推荐答案

Mongoengine允许文档继承。定义类时,元属性 allow_inheritance 用于允许对此特定类进行子类化。
_cls _types 字段用于标识对象所属的类。

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

现在考虑一个名为 StackOverFlowUser 的文档:本文档继承自用户文档,并为用户保存一些StackOverflow相关信息:

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

对于这两个文档类, mongoengine将使用名为 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.

要区分对象所属的类,将使用_cls _types 字段。

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

对于用户对象:

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

对于 StackOverFlowUser 对象:

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

如果您确定文档不具有子类文档,则设置 allow_inheritance False ,并且mongoengine将不会保存 _cls _types 该文件的字段。

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.

这篇关于MongoEngine _types和_cls字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆