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'> 

它看起来像嵌入式文档没有被翻译成一个对象。我不确定这是一个错误,还是我误解了这个概念。感谢您的任何建议。

在0.8.3中,您将不得不手动重构它,这是一个错误 - 所以我打开了#449并在master中修复。 0.8.4将在本周晚些时候到期。

+0

感谢您的回答。所以这是一个错误,我会等待下一个版本。 – manuel

+0

刚刚获得新版本,现在按预期工作。非常感谢。 – manuel

报价从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