-
-
Save macagua/d0ecd80adbed1ca0d983d285103a4234 to your computer and use it in GitHub Desktop.
Flask SqlAlchemy MySQL ON DUPLICATE KEY UPDATE returning auto increment id UPSERT HOTNESS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from app import db | |
from sqlalchemy import func | |
from sqlalchemy.dialects.mysql import insert | |
def upsert(model, insert_dict): | |
"""model can be a db.Model or a table(), insert_dict should contain a primary or unique key.""" | |
inserted = insert(model).values(**insert_dict) | |
upserted = inserted.on_duplicate_key_update( | |
id=func.LAST_INSERT_ID(model.id), **{k: inserted.inserted[k] | |
for k, v in insert_dict.items()}) | |
res = db.engine.execute(upserted) | |
return res.lastrowid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment