Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL string replace using SQLAlchemy

Is there a way in SQLAlchemy to perform a MySQL string replace. I'd like to find a way to do the following in SQLAlchemy core.

UPDATE your_table
SET your_field = REPLACE(your_field, 'from_str', 'to_str')
WHERE your_field LIKE '%from_str%'
like image 333
Luke Avatar asked Dec 24 '22 15:12

Luke


1 Answers

Yes, read more about it on Column Elements and Expressions, but the key point is to use func.MY_FUNCTION:

func.REPLACE(YourTable.your_field, 'from_str', 'to_str')

If you perform update from query, it might look like this:

updated_rows = (
    session.query(YourTable)
    .filter(YourTable.your_field.like('%est%'))
    .update({YourTable.your_field: func.replace(YourTable.your_field, 'from_str', 'to_str')},
            synchronize_session=False)
    )
print("Updated {} rows".format(updated_rows))
like image 148
van Avatar answered Dec 28 '22 09:12

van