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)
I get this error "AttributeError: 'Event' object has no attribute 'aa' "
Your help will be greatly appreciated.