Search code examples
pythonflasksqlalchemyflask-sqlalchemy

Get column name by using variable in sqlalchemy


So say I have a flask route and i get a variable "column_name" from it and new value as "data" in the post request:

@app.route('/<lead_id>/<column_name>/update', methods=['POST'])
def update_user_column(lead_id, column_name):

Now i need to run a db query to find that value and check if its changed:

new_value = request.json
current_value = db.session.query(getattr(Lead, column_name)).filter_by(id=lead_id).first()
if new_value != str(*current_value):

Now i need to update the lead column value with the new value but i cant get the column_value to use in the following expression:

lead.column_name = new_value

This is where i have an issue because the actual column name is the value of the "column_name" variable while sqlalchemy is using "column_name" as the column name instead of its value.

Any help would be appreciated.


Solution

  • You can use the setattr builtin I think but if you are not already you should restrict it somehow otherwise I think this could probably be abused.

    if column_name in writable_column_names:
        setattr(lead, column_name, new_value)