python - mongoengine 在 DynamicField 中嵌入文档

标签 python mongodb mongoengine

我尝试将文档嵌入到动态字段中。但是当我稍后尝试访问它时,它不再是文档对象,它只是一个字典。

这是我刚刚编写的示例代码:

#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并固定在主人身上。 0.8.4 将于本周晚些时候发布。

关于python - mongoengine 在 DynamicField 中嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18324753/

相关文章:

python:polySplitRing Insert with Edge flow on multiple edges

python - 一次分配多个变量,Python

mongodb - 创建副本集时出错 - MongoDb

node.js - 管理数据库中不断变化的数据

django - 提供给 EmbeddedDocumentField 的嵌入式文档实例无效

python - 无法在 rospy 中发布订阅的主题

python - 在Python Tkinter : What option can I use to resize a window?

用于 HL7-FHIR 的 MongoDB

python - 在 MongoEngine 中增加一个 IntField

python - Django + MongoDB