如何使用字符串表示sqlalchemy对象属性? [英] how can i use a string to to represent an sqlalchemy object attribute?
问题描述
我正在用SQLalchemy和WTForms编写Flask应用程序.
I am writing a Flask application with SQLalchemy and WTForms.
数据库更新遇到问题...我有很多对象表字段正在尝试更新.
Trouble with database updates... I have many object table fields I am trying to update.
所以我从这里开始...
so I started with this...
# this works great but needs many lines of code
event.evt_num = form.evt_num.data
event.evt_name = form.evt_name.data
event.evt_location = form.evt_location.data
event.evt_address = form.evt_address.data
event.evt_city = form.evt_city.data
event.evt_state = form.evt_state.data
...
尽管上面的代码片段有效,但实际上它是巨大的.因此,我想变得更聪明,并遍历属性以更新数据库.所以我尝试了以下...
While the above snippet works, in reality it is huge. So I would like to be smarter and iterate thru the attributes to update the database. So I tried the following...
event_fields = ('evt_num', 'evt_name', 'evt_location', 'evt_address',
'evt_city', 'evt_state', 'evt_zip', 'evt_notes')
for aa in event_fields:
print "form data", getattr(form, aa).data # prints posted form data
print "db data", getattr(event, aa) # prints posted data from database
if getattr(form, aa).data != getattr(event, aa): # if form data shows a change
setattr(event, aa, getattr(form, aa).data) # update database does not work
db_change = True
session.flush()
...
此行不适用于更新数据库:
This line doesnt work to update the database:
setattr(event, aa, getattr(form, aa).data)
我收到此错误" AttributeError:'事件'对象没有属性'aa'"
我们将非常感谢您的帮助.
Your help will be greatly appreciated.
推荐答案
如果您像这样进行重组怎么办?
What if you restructured like this?
event_fields = ('evt_num', 'evt_name', 'evt_location', 'evt_address',
'evt_city', 'evt_state', 'evt_zip', 'evt_notes')
for aa in event_fields:
form_data = getattr(form, aa).data
db_data = getattr(event,aa)
print "form data", form_data # prints posted form data
print "db data", db_data # prints posted data from database
if form_data != db_data: # if form data shows a change
setattr(event, aa, form_data) # update database now works
db_change = True
session.flush()
...
这样,您对getattr()
的调用减少了,并且可能会稍微优化代码.
This way, you make fewer calls to getattr()
and maybe optimize your code slightly.
这篇关于如何使用字符串表示sqlalchemy对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!