shahjapan
shahjapan

Reputation: 14335

how to save django object using dictionary?

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

Answers (4)

toast38coza
toast38coza

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:

  • be aware that .update does not trigger signals
  • You may want to put a check in there to make sure that only 1 result is returned before updating (just to be on the safe side). e.g.: if p1.count() == 1: ...
  • This may be a preferable option to using __ 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

Daniel Roseman
Daniel Roseman

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

user257858
user257858

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

Related Questions