MongoEngine Document Object made using from_json doesn't save

守給你的承諾、 提交于 2019-11-30 02:24:44
BabbarTushar

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

This worked for me.

bindi

from_json() is convert to JSON data an unsaved document instance. Do save of unsaved document is use parameter force_insert=True.

...
>>> User.objects
[<User: test1-12345>]
>>> u2.save()
>>> User.objects
[<User: test1-12345>]
>>> u2.save(force_insert=True)
>>> User.objects
[<User: test1-12345>, <User: test2-12345>]

But, your code I can.

I can not code here. (I need fixture data of unit test.)

I environment Django 1.6.5 and mongoengine 0.8.7

>>> json_data1 = u1.to_json()
>>> User.objects.delete() # or User.drop_collection()
>>> User.objects
[]
>>>
...
# json_data1 to dump for pickle. Next load for pickle.
...
>>> u1 = User.from_json(json_data1)
>>> u1.save()
>>> User.objects
[]
>>> u1.save(force_insert=True)
>>> User.objects
[<User: test1-12345>]
>>>

force_insert=True is only try to create a new document.

Every time use force_insert=True is create a new document.

Use force_insert=False is get document in database.

You are assigning u2 to the result of from_json(), and losing reference to the original User object.

Change u2 = u2.from_json(... to u2.from_json(...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!