[英]Save record from dictionary using MongoAlchemy
My model class for user collection looks like this.我的用户集合模型类如下所示。
class User(UserMixin,db.Document):
config_extra_fields = 'ignore'
first_name = StringField()
last_name = StringField()
def get_id(self):
return str(self.mongo_id)
To insert value to this collection I use the following code:要向该集合插入值,我使用以下代码:
user = User(first_name="FN", last_name="LN", finale_name="SOMENAME")
user.save()
I tried setattr
, But it is ignoring the attributes that are not defined in the class.我试过setattr
,但它忽略了类中未定义的属性。
Its working fine and even the finale_name
is added to the document.它工作正常,甚至finale_name
也被添加到文档中。 However, I am unable to insert it dynamically.但是,我无法动态插入它。
Can I insert a dictionary to mongo using that class?我可以使用该类向 mongo 插入字典吗? Something like this?像这样的东西?
user = User({
"first_name": "NEW NAME",
"last_name": "LAST NAME",
"username": "USER NAME",
"one_more": "Hello"
})
Use below code:使用以下代码:
data = {
"first_name": "NEW NAME",
"last_name": "LAST NAME",
"username": "USER NAME",
"one_more": "Hello"
}
user = User(**data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.