我在 mongo 引擎中有一个文档,其中有一个嵌入式文档。这是我的模型:
class Problem(EmbeddedDocument):
id = ObjectId()
class Result(EmbeddedDocument):
problem = ReferenceField('Problem')
class Contest(Document):
problem = EmbeddedDocumentField(Problem)
现在我想从Result
模型访问Problem
。我该怎么做?
最佳答案
EmbeddedDocument
和 Document
的根本区别在于 EmbeddedDocument
仅存在于 Document
中。
EmbeddedDocument
is aDocument
that isn’t stored in its own collection.EmbeddedDocuments
should be used as fields on Documents through theEmbeddedDocumentField
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/