From here ,
I need to update my existing document data using from_json
.
When I am using from_json
like
>> user = User.objects(pk=2).first()
>> print user.to_json()
above shows
>> {"_id": 1, "_cls": "User", "name": "OldName"}
now I update existing user
object
>> user = user.from_json(json.dumps({"_id": 1, "_cls": "User", "name": "NewName"}))
>> user.save()
>> print user.to_json()
it shows
>> {"_id": 1, "_cls": "User", "name": "NewName"}
But it cannot update in DB.
Again I querying same user
it shows
>> {"_id": 1, "_cls": "User", "name": "OldName"}
My Question is how can I update existing data using document object method from_json
?
That I'm afraid is a common issue and probably not been resolved yet, this is a link to the source code of MongoEngine and you can search "from_json" to see if you can hack around by figuring out what this function is actually doing: https://github.com/MongoEngine/mongoengine/blob/master/mongoengine/queryset/base.py ;
For me, I simply iterate over the (key, value)
of the json data and set that manually by:
Batman = User.objects.get('user_id'='blah')
data = {'username':'batman', 'password':'iLoveGotham'}
for (key, val) in data.items():
Batman[key] = val
Batman.save()
It works, but hopefully the from_json
function could actually work so that this process would become more elegant.
For me the following worked:
user.update(**mydictname) #mydictname contains the dictionary of values I want to update
user.save()
user.reload() #not doing this makes the changes available only after the object is reloaded elsewhere
Does it not update if you search in a Mongo Shell for the document either? If not, stop reading here . Saving does not automatically update the object, but I think if you call something like:
>> user = user.from_json(json.dumps({"_id": 1, "_cls": "User", "name": "NewName"}))
>> user.save()
>> user.reload()
>> print user.to_json()
Just learning Mongoengine myself, but here is a good resource: http://docs.mongoengine.org/guide/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.