使用from_json制成的MongoEngine文档对象无法保存 [英] MongoEngine Document Object made using from_json doesn't save
本文介绍了使用from_json制成的MongoEngine文档对象无法保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用from_json方法构建文档对象. object.save()不会引发任何错误,但是文档未插入mongo.
I am trying to build a document object using from_json method. object.save() throws no error, but the document is not inserted in mongo.
另一方面,如果我通过为每个字段分配值来创建对象,那么它将正常工作.
On the other hand if I make the object by assigning values to each of the fields, it works fine.
我找不到原因.下面是这两种情况的代码.
I am unable to find the reason for this. Below is the code for both the cases.
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import json, datetime
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {'DB': 'test','host': 'localhost'}
app.config["SECRET_KEY"] = "mySecretKey"
db = MongoEngine(app)
class User(db.Document):
user_id = db.StringField(max_length=16, primary_key = True)
username = db.StringField(min_length=8)
email = db.EmailField(required = True, unique = True)
password = db.StringField(required = True)
date_of_birth = db.DateTimeField()
gender = db.StringField(choices = ('M', 'F'))
'''
This one works. This will add a user in local mongodb(test)
'''
u1 = User()
u1.username = 'test12345'
u1.user_id = 'testid12345'
u1.email = 'test@test.com'
u1.password = 'testerpass'
u1.save()
'''
This one doesn't works.
'''
u2 = User()
temp_json = {'username':'test2_12345','user_id':'testid2@12345','password':'testerpass2','email':'test2@test.com'}
u2 = u2.from_json(json.dumps(temp_json))
u2.save()
推荐答案
可以使用**kwargs
初始化mongoengine文档对象.因此,使用此方法,我们可以通过以下方式实现from_json
功能:-
A mongoengine document object can be initialised with **kwargs
. Thus using this we can implement the from_json
functionality in the following way :-
obj_dict = {
'key1' : 'value1',
'key2' : 'value2'
}
user = User(**obj_dict) # User is a mongoengine document object
这对我有用.
这篇关于使用from_json制成的MongoEngine文档对象无法保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文