How to save django object using dictionary?

Is there a way to save the model using a dictionary

eg. it works fine

p1 = Poll.objects.get(pk=1)

p1.name = 'poll2'
p1.descirption = 'poll2 description'

p1.save()

but what if I have a dictionary, for example {'name': 'poll2', 'description:' poll2 description '}

there is an easy way to save such a dictionary directly in the survey

+3
source share
2 answers

The drmegahertz solution works if you create a new object from scratch. In your example, however, you seem to want to update an existing object. You do this by accessing the attribute __dict__that every Python object has:

p1.__dict__.update(mydatadict)
p1.save()
+22
source

, :

data_dict = {'name': 'foo', 'description': 'bar'}

 # This becomes Poll(name='foo', description='bar')
 p = Poll(**data_dict)
 ...
 p.save()
+15

Source: https://habr.com/ru/post/1742412/


All Articles