Skip to content

Instantly share code, notes, and snippets.

@macagua
Forked from vanpelt/upsert.py
Created April 1, 2023 22:25
Show Gist options
  • Save macagua/d0ecd80adbed1ca0d983d285103a4234 to your computer and use it in GitHub Desktop.
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
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