Update an object with a dictionary

141 views
Skip to first unread message

Paolo Corti

unread,
Jun 10, 2009, 12:27:36 PM6/10/09
to Django users
Hi
is it possible to update an object with a dictionary?

I tried something like this:
myobject.save(force_update=True, **my_dict)

getting an error, though:
TypeError at ...
save() got an unexpected keyword argument 'myfieldname'

I wouldn't like to iterate the dictionary, neither to delete and
create the object again using the dictionary, is there a best
approach?

thanks
Paolo

Daniel Roseman

unread,
Jun 10, 2009, 3:13:46 PM6/10/09
to Django users
The error is in passing the dictionary to the save() method. If you've
got an existing object and you want to update it, this will work:
my_object.__dict__.update(my_dict)
myobject.save()
--
DR.

Kevin Teague

unread,
Jun 10, 2009, 3:17:29 PM6/10/09
to Django users
.save() is only for persisting the object to disk, not for modifying
objects. To update any Python object from a dictionary is as easy as:

for k,v in d.items(): setattr(myobject, k, v)

Paolo Corti

unread,
Jun 10, 2009, 5:00:46 PM6/10/09
to Django users

>
> .save() is only for persisting the object to disk, not for modifying
> objects. To update any Python object from a dictionary is as easy as:
>
> for k,v in d.items(): setattr(myobject, k, v)

this is also what i came to.
But curious to try the Daniel's approach, will let you know
best regards

Kevin Teague

unread,
Jun 10, 2009, 5:56:01 PM6/10/09
to Django users
__dict__ is an attribute of every Python object. It's typically only
an internal detail, and generally not accessed directly. One area
where __dict__ modification would differ from attribute access is with
an attribute that's a property. Modifying the __dict__ would ignore
the property getter/setter code, where as modifying the attribute will
still invoke those methods. In other words, __dict__ manipulation
breaks encapsulation ... although in rare cases this is what you want
to do!


>>> class Foo(object): pass
...
>>> f = Foo()
>>> f.__dict__
{}
>>> f.cat = 'dog'
>>> f.__dict__
{'cat': 'dog'}
>>> f.__dict__['cow'] = 'moo'
>>> f.cow
'moo'

Alex Gaynor

unread,
Jun 10, 2009, 5:59:18 PM6/10/09
to django...@googlegroups.com
Technically it's not on every Python object, any object that defines __slots__ won't have it.

Alex

--
"I disapprove of what you say, but I will defend to the death your right to say it." --Voltaire
"The people's good is the highest law."--Cicero
Reply all
Reply to author
Forward
0 new messages