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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With