Last active
January 26, 2024 14:09
-
-
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)
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
# 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
Thanks!