2013-08-19 67 views
5

我嘗試將文檔嵌入到動態字段中。但是當我稍後嘗試訪問它時,它不再是文檔對象,它只是一個字典。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'> 

它看起來像嵌入式文檔沒有被翻譯成一個對象。我不確定這是一個錯誤,還是我誤解了這個概念。感謝您的任何建議。

回答

2

在0.8.3中,您將不得不手動重構它,這是一個錯誤 - 所以我打開了#449並在master中修復。 0.8.4將在本週晚些時候到期。

+0

感謝您的回答。所以這是一個錯誤,我會等待下一個版本。 – manuel

+0

剛剛獲得新版本,現在按預期工作。非常感謝。 – manuel

1

報價從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') 

希望有所幫助。

+0

我知道EmbeddedDocumentField類型。但是我想使用不同類型的字段,因此我選擇了DynamicField,因爲這應該能夠存儲所有內容。 – manuel

+0

明白了,但你可以暫時切換到'EmbeddedDocumentField'並檢查它是否拋出相同的錯誤?它不應該,但請檢查。 – alecxe

+0

EmbeddedDocumentField正常工作。沒有錯誤。 – manuel