tags:

views:

111

answers:

2

I have a dictionary that I would like to iterate through and copy the key-value pairs into an object in Python. The dictionary is POST, and the object is a Model (in Django, perhaps Django has better way to do this).

In PHP, I'd be able to use variable assignments:

foreach($post as $key => $value) {
    $my_model->$key = $value;
}

And in Javascript I could treat the object with array assignments:

for(var key in post) {
    my_model[key] = post[key];
}

However, I can't seem to do so in Python. The only way I've seen is by using the objects __dict__ property, and it feels ever so slightly dirty. Plus it can raise KeyErrors.

+3  A: 

You can use setattr, but it's likely the wrong way to do it in your context. You should look at Django's ModelForms documentation first.

oggy
I've seen the ModelForms. the issue i have with them is that if I didn't POST all values of the Model, it complains. My original goal is to retrieve the model from the DB, change the properties I've posted, and then save it back
seanmonstar
Then you're not using the form right. If you don't want to post all the values, use `exclude` to exclude them from the field (or `fields` to only include the ones you need).
Daniel Roseman
+5  A: 
for key, value in post.iteritems():
    setattr(my_model, key, value)
Denis Otkidach
I think oggy is right in stating that he should delve more into ModelForms. Not that his doesn't work, and it is what he is asking for, but he did tag the issue as django...
celopes
Indeed, I tagged it Django in case an answer appeared that was a better way of doing things in Django, perhaps like ModelForms...
seanmonstar