Skip to content

Instantly share code, notes, and snippets.

@malexer
Last active January 26, 2024 14:09
Show Gist options
  • Save malexer/0647b208b2f1c48ec93e1bd157dc67c0 to your computer and use it in GitHub Desktop.
Save malexer/0647b208b2f1c48ec93e1bd157dc67c0 to your computer and use it in GitHub Desktop.
Modelling UPSERT in SQLAlchemy (well actually it is not upsert but speed improvement is significant in comparison with simple session.merge)
# Note: it is a copy of great answer by "mgoldwasser" from Stackoverflow
# Check the original answer here: http://stackoverflow.com/a/26018934/1032439
# Imagine that post1, post5, and post1000 are posts objects with ids 1, 5 and 1000 respectively
# The goal is to "upsert" these posts.
# we initialize a dict which maps id to the post object
my_new_posts = {1: post1, 5: post5, 1000: post1000}
for each in posts.query.filter(posts.id.in_(my_new_posts.keys())).all():
# Only merge those posts which already exist in the database
db.session.merge(my_new_posts.pop(each.id))
# Only add those posts which did not exist in the database
db.session.add_all(my_new_posts.values())
# Now we commit our modifications (merges) and inserts (adds) to the database!
db.session.commit()
@chienjchienj
Copy link

Thanks!

@kid101
Copy link

kid101 commented Mar 30, 2021

Great post! Thanks

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