views:

66

answers:

2

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

+6  A: 

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()
drmegahertz
+4  A: 

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()
Daniel Roseman