MongoEngine:将字段添加到动态文档 [英] MongoEngine: Adding Fields to Dynamic Document

查看:445
本文介绍了MongoEngine:将字段添加到动态文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将动态字段存储到文档中,但是每个文档可以具有不同的字段.

I would like to store dynamic fields to the document, but each document can have different fields.

例如:

Class SampleDoc(DynamicDocument):
   xyz = StringField()

df = "field1"
a = SampleDoc()
a.df = "testing"
a.save()

如果运行上述程序,则mongodb文档如下所示.

If i run the above program, the mongodb document looks like the following.

{ "_id" : ObjectId("53905681e5ba5b3bfd1f5242"), "_cls" : "DataPoint", "df" : "testing" }

但是我想要的是字段名称应该是"field1"而不是"df".

but what i want is that the field name should be "field1" instead of "df" like this..

{ "_id" : ObjectId("53905681e5ba5b3bfd1f5242"), "_cls" : "DataPoint", "field1" : "testing" }

这只是示例代码,所以我知道df值是多少,但实际上我不知道df保持什么值.那么在存储时动态命名字段的方法是什么.

This is just a sample code so i know what df value is, but in real i don't know what value df holds. So what is the way to name a field dynamically while storing.

还有一个类似的问题在Mongoengine中将密钥用作值,但是该解决方案建议使用DictField(),但我不想使用它.

There is a similar question using key as value in Mongoengine, but the solution suggests to use DictField(), but i don't want to use it.

推荐答案

在源代码中查看BaseDocument.py之后,找到了解决方案.

Found the solution after looking at BaseDocument.py in the source code.

df = "field1"
a = SampleDoc()
a.__setattr__(df,"testing")
a.save()

这篇关于MongoEngine:将字段添加到动态文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆