8

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

4 Answers 4

34

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()
Sign up to request clarification or add additional context in comments.

1 Comment

This can be very useful for upholding the DRY principle while doing tricky stuff on the save() method of ModelForm. For example, I have a a form that copies cleaned_data to a new dictionary, then deletes certain fields from it -- because values from other fields make them irrelevant or contradictory -- then saves only the remaining fields in that dictionary onto the instance (and the instance is an object that has already been initialized).
30

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

Comments

2

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

Comments

1

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__.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.