AppEngine Python - updating entity properties without twenty elif statements
Suppose I have an AppEngine model defined with twenty different StringProperty properties. And then I have a web form, which POSTs updated values for an entity of this model. I end up with something like this after reading in the form data:
entity_key['name'] = 'new_name'
entity_key['city'] = 'new_city'
entity_key['state'] = 'new_state'
etc...
To actually assign these values to the entity, I'm presently doing something like this:
if property == 'name':
entity.name = entity_key['name']
elif property == 'city':
entity.city = entity_key['city']
elif property == 'state':
entity.state = entity_key['state']
etc...
Is there any way to assign the property values without twenty elif statements? I see that there is the model.properties() function, but I don't see anyway to tie all this toge开发者_运维知识库ther.
All help is appreciated.
Thank you.
The same effect as for your if
/ elif
tree could be obtained by a single statement:
setattr(entity, property, entity_key[property])
This is just elementary Python, working the same way in every Python version since 1.5.2 (and perhaps earlier -- I wasn't using Python that many years ago!-), and has nothing specifically to do with App Engine, nor with Django, nor with the combination of the two.
Cool. Just for others' reference, the following two snippets are identical:
entity.some_property = "cat";
setattr(entity, "some_property", "cat")
I did know about the setattr function, Alex, so thanks for helping me out.
精彩评论