Created
March 20, 2018 06:33
-
-
Save vanpelt/1568296c0d6c97a4472ce1fcde73fc6c 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 |
Thanks for this! :)
Thanks a lot! ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@cjauvin I'm so glad you found it and were able to use it!