Method from_json
of mongoengine
ModelClass
used for:
Converts json data to an unsaved document instance
If i send to a server json with some changed fields and trying to convert in to unsaved document instance, they dont track a _changed_fields
in model eg _changed_fields
is always empty.
data = self.request.data # json representation of object
model_instance = SomeModel.from_json()
print(model_instance._changed_fields) # get empty list
As i know .save
method of ModelInstance only save a changed fields and check it in _changed_fields
property. So if this property is always empty - unable to save model instance created via from_json
method.
Question is - how can i save model instance created from json?
Can't you just do this?
data = self.request.data
model_instance = SomeModel(**data)
print(model_instance._changed_fields) # should not be empty
model_instance.save() # should work
Explanations:
In python, if a function or a class takes arguments (args) and named arguments (kwargs), one can populate them from respectively a list/tuple (my_list) and a dictionary (my_dict).
Requirements:
Example:
def foo(a, b, c=None, d=1):
pass
class Foo(object):
def __init__(self, a, b, c=None, d=1):
pass
my_list = [1, 2]
my_dict = {'c': 3, 'd': 4}
you can do:
test = foo(*my_list, **my_dict)
or
obj = Foo(*my_list, **my_dict)
I hope it helps.
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.