mongoengine在DynamicField中嵌入文档
问题描述:
我尝试将文档嵌入到动态字段中。但是当我稍后尝试访问它时,它不再是文档对象,它只是一个字典。mongoengine在DynamicField中嵌入文档
下面是示例代码我刚刚组成:
#defining the documents
class Embed(EmbeddedDocument):
field_1 = StringField(db_field='f')
class Doc(Document):
myid = IntField(required=True, unique=True, primary_key=True)
embed_me = DynamicField(db_field='e')
field_x = StringField(db_field='x')
然后创建一个新文档,并将其保存:
connect('test')
# the embedded part
embed = Embed(field_1='this is a test')
# the document with the embedded document
doc = Doc(pk=2)
doc.embed_me = embed
doc.save()
到目前为止,一切正常。这是我的数据库获取:
# > db.doc.find()
# { "_id" : 1, "e" : { "f" : "this is a test", "_cls" : "Embed" } }
但现在,如果我要求的文件,并尝试从嵌入文档访问值我得到一个异常:
doc, c = Doc.objects.get_or_create(pk=1)
仅供参考:在主文档访问工作
print doc.field_x
> None
还引用了:在字典看起来不错,只是与嵌入文档的名称没有翻译
print doc.__dict__
> {'_created': False, '_data': {'myid': 1, 'embed_me': {u'_cls': u'Embed', u'f': u'this is a test'}, 'field_x': None}, '_changed_fields': [], '_initialised': True}
和现在,而试图访问嵌入文档,异常升高
print doc.embed_me.field_1
> File "embed_err.py", line 31, in <module>
print doc.embed_me.field_1
AttributeError: 'dict' object has no attribute 'field_1
是什么类型呢?
type(doc.embed_me)
> <type 'dict'>
它看起来像嵌入式文档没有被翻译成一个对象。我不确定这是一个错误,还是我误解了这个概念。感谢您的任何建议。
答
报价从docs:
类mongoengine.EmbeddedDocument(* ARGS,** kwargs)
是 并不存储在自己收集的文件。通过EmbeddedDocumentField字段类型,EmbeddedDocuments应该被用作文档上的字段 。
您应该Doc
文档定义EmbeddedDocumentField
而不是DynamicField
:
class Doc(Document):
myid = IntField(required=True, unique=True, primary_key=True)
embed_me = EmbeddedDocumentField(Post, db_field='e')
field_x = StringField(db_field='x')
希望有所帮助。
感谢您的回答。所以这是一个错误,我会等待下一个版本。 – manuel
刚刚获得新版本,现在按预期工作。非常感谢。 – manuel