我嘗試將文檔嵌入到動態字段中。但是當我稍後嘗試訪問它時,它不再是文檔對象,它只是一個字典。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'>
它看起來像嵌入式文檔沒有被翻譯成一個對象。我不確定這是一個錯誤,還是我誤解了這個概念。感謝您的任何建議。
感謝您的回答。所以這是一個錯誤,我會等待下一個版本。 – manuel
剛剛獲得新版本,現在按預期工作。非常感謝。 – manuel