How Can I Use A String To To Represent An Sqlalchemy Object Attribute?
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... # th
Solution 1:
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()
...
This way, you make fewer calls to getattr()
and maybe optimize your code slightly.
Solution 2:
Per user:coralv's comment, I resolved the problem by storing the getattr contents into a variable instead of having it as a part of the setattr function. Code ends up 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:
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
val = getattr(form, aa).data
setattr(event, aa, val) # update database now works
db_change = True
session.flush()
...
Post a Comment for "How Can I Use A String To To Represent An Sqlalchemy Object Attribute?"