【问题标题】:mongoengine embeded document in a DynamicFieldmongoengine 在 DynamicField 中嵌入文档
【发布时间】:2013-08-20 16:36:33
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python mongodb mongoengine


    【解决方案1】:

    在 0.8.3 中,您必须手动重建它,这是一个错误 - 所以我打开了 #449 并在 master 中修复。 0.8.4 将于本周晚些时候发布。

    【讨论】:

    • 感谢您的回答。所以这是一个错误,我会等待下一个版本。
    • 刚拿到新版本,现在可以正常使用了。非常感谢。
    【解决方案2】:

    引用docs:

    类 mongoengine.EmbeddedDocument(*args, **kwargs)

    一份文件 不存储在自己的集合中。应该使用 EmbeddedDocuments 通过 EmbeddedDocumentField 字段类型作为 Documents 上的字段。

    您应该在 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')
    

    希望对您有所帮助。

    【讨论】:

    • 我知道 EmbeddedDocumentField 类型。但是我想将该字段用于不同的类型,所以我选择了 DynamicField,因为它应该能够存储所有内容。
    • 知道了,但你能暂时切换到EmbeddedDocumentField 并检查它是否抛出相同的错误吗?它不应该,但请检查。
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多