AppEngine Python - 无需二十个 elif 语句即可更新实体属性
假设我有一个用二十个不同的 StringProperty 属性定义的 AppEngine 模型。然后我有一个 Web 表单,它发布该模型实体的更新值。在读取表单数据后,我最终得到类似的结果:
entity_key['name'] = 'new_name'
entity_key['city'] = 'new_city'
entity_key['state'] = 'new_state'
etc...
为了实际将这些值分配给实体,我目前正在做这样的事情:
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...
有没有办法在没有二十个 elif 语句的情况下分配属性值?我看到有 model.properties() 函数,但无论如何我看不到将所有这些结合在一起。
感谢所有帮助。
谢谢。
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 together.
All help is appreciated.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过一条语句可以获得与
if
/elif
树相同的效果:这只是基本的 Python,自 1.5.2 以来的每个 Python 版本都以相同的方式工作(也许更早——很多年前我并没有使用Python!——),并且与App Engine、Django 或两者的组合没有任何具体关系。
The same effect as for your
if
/elif
tree could be obtained by a single statement: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.
凉爽的。仅供其他人参考,以下两个片段是相同的:
我确实知道 setattr 函数,Alex,所以感谢您帮助我。
Cool. Just for others' reference, the following two snippets are identical:
I did know about the setattr function, Alex, so thanks for helping me out.