Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jftuga
Forked from malexer/sqlalchemy_upsert.py
Created May 19, 2021 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jftuga/6e6275a0430e1a09598bec90b345557c to your computer and use it in GitHub Desktop.
Save jftuga/6e6275a0430e1a09598bec90b345557c 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment