Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bulk_update_mappings by field which is different than private key

I have a class with db fields

id = db.Column(db.BigInteger, primary_key=True) 
uuid = db.Column(
  UUID(as_uuid=True), unique=True, nullable=True, default=uuid.uuid4
) 
name = db.Column(db.String(50), nullable=False)

And then I wanted to bulk update by 'uuid' field, not id as by default:

updates = []
for upd in body['new_data']:
    update = {
        'uuid': upd['uuid'],
        'name': upd['name'],
    }
    updates.append(update)

db.session.bulk_update_mappings(MyClass, updates)

But I have an error that there are no matches. How can I do bulk update by 'uuid' field?

like image 614
Tony Avatar asked Dec 21 '25 19:12

Tony


1 Answers

According to the official SQLAlchemy documentation, it will not be possible.

All those keys which are present and are not part of the primary key are applied to the SET clause of the UPDATE statement; the primary key values, which are required, are applied to the WHERE clause.

source: SQLAlchemy documentation

If you want an alternative, try using on_conflict_do_update() which works like an upsert, and you can specify on which column should be the where clause done.

Here is the documentation explaining how it works in detail.

like image 194
Epion Avatar answered Dec 23 '25 07:12

Epion