加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – mongoengine在DynamicField中嵌入文档

发布时间:2020-12-16 21:49:53 所属栏目:Python 来源:网络整理
导读:我尝试将文档嵌入到动态字段中.但是当我稍后尝试访问它时,它不再是文档对象,它只是一个字典. 这是我刚刚编写的示例代码: #defining the documentsclass Embed(EmbeddedDocument): field_1 = StringField(db_field='f') class Doc(Document): myid = IntFiel

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

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

#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中得到的:

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

另请参考:dict看起来没问题,但嵌入式文档中的名称未翻译

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 

它是什么类型的?

 type(doc.embed_me)
 > 

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

最佳答案
在0.8.3中你将不得不手动重建它,这是一个错误 – 所以我打开了#449并修复了主人. 0.8.4将在本周晚些时候到期.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读