Reputation: 14335
is there a way that I can save the model by using dictionary
for e.g. this is working fine,
p1 = Poll.objects.get(pk=1)
p1.name = 'poll2'
p1.descirption = 'poll2 description'
p1.save()
but what if I have dictionary like { 'name': 'poll2', 'description: 'poll2 description' }
is there a simple way to save the such dictionary direct to Poll
Upvotes: 8
Views: 15195
Reputation: 9066
You could achieve this by using update on a filterset:
e.g.:
data = { 'name': 'poll2', 'description: 'poll2 description' }
p1 = Poll.objects.filter(pk=1)
p1.update(**data)
Notes:
.update
does not trigger signalsif p1.count() == 1: ...
__
methods such as __dict__.
Upvotes: 1
Reputation: 81
I find only this variant worked for me clear. Also in this case all Signals will be triggered properly
p1 = Poll.objects.get(pk=1)
values = { 'name': 'poll2', 'description': 'poll2 description' }
for field, value in values.items():
if hasattr(p1, field):
setattr(p1, field, value)
p1.save()
Upvotes: 2
Reputation: 599610
drmegahertz's solution works if you're creating a new object from scratch. In your example, though, you seem to want to update an existing object. You do this by accessing the __dict__
attribute that every Python object has:
p1.__dict__.update(mydatadict)
p1.save()
Upvotes: 33
Reputation:
You could unwrap the dictionary, making its keys and values act like named arguments:
data_dict = {'name': 'foo', 'description': 'bar'}
# This becomes Poll(name='foo', description='bar')
p = Poll(**data_dict)
...
p.save()
Upvotes: 30