python - 从mongoengine中的另一个嵌入式文档访问嵌入式文档

标签 python mongodb mongoengine

我在 mongo 引擎中有一个文档,其中有一个嵌入式文档。这是我的模型:

class Problem(EmbeddedDocument):
    id = ObjectId()

class Result(EmbeddedDocument):
    problem = ReferenceField('Problem')

class Contest(Document):
    problem = EmbeddedDocumentField(Problem)

现在我想从Result 模型访问Problem。我该怎么做?

最佳答案

EmbeddedDocumentDocument 的根本区别在于 EmbeddedDocument 仅存在于 Document 中。

EmbeddedDocument is a Document that isn’t stored in its own collection. EmbeddedDocuments should be used as fields on Documents through the EmbeddedDocumentField field type.

因此 EmbeddedDocument 不能有主键,EmbeddedDocument 它只是文档中的一个字典。详见documentation

id = ObjectId() 这不是字段声明。列出了所有可能的字段 there .由于要声明主键字段,您需要在字段参数中使用 primary_key=True

problem = ReferenceField('Problem') EmbeddedDocument 不能引用,因为它不是字段。因此,声明嵌入字段的正确方法如下所示:problem = EmbeddedDocumentField(Problem)

关于python - 从mongoengine中的另一个嵌入式文档访问嵌入式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996604/

相关文章:

python - 通过 python 创建一个 vlan 并将其添加到网络命名空间

javascript - SimpleSchema 错误 : After filtering out keys not in the schema, 您的修饰符现在为空

node.js - mongoose/nodejs 中的验证错误

django - 将 mongoengine 与 models.ImageField 一起使用

python - 如何在 Python 中创建一组在 Mongodb 中唯一的字段组合

python - mongoengine 操作的原子性如何

Python——递归字符串查找

用于用户输入的python库

python - 动态添加属性到 Django 模型

node.js - 使用PM2运行完整的开发环境