Skip to content

Instantly share code, notes, and snippets.

@vanpelt
Created March 20, 2018 06:33
Show Gist options
  • Save vanpelt/1568296c0d6c97a4472ce1fcde73fc6c to your computer and use it in GitHub Desktop.
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
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
@vanpelt
Copy link
Author

vanpelt commented Jun 4, 2020

@cjauvin I'm so glad you found it and were able to use it!

@GeorgeVince
Copy link

Thanks for this! :)

@Kain-90
Copy link

Kain-90 commented Mar 2, 2023

Thanks a lot! ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment