lundi 1 novembre 2021

SQLAlchemy ^=1.4, mass insert or update if exists

Let's say that I have a list of sqlalchemy objects [obj1, obj2..., objn] that I would like to insert into sqlite table if they don't exist, or update if they exist in table.

This list represents successive objects from certain time range. I could have a list with mix of object, some of them that exist and some that don't exist in table.

I could do something like this:

for obj in list:
    saved_obj = select obj
    if saved_obj:
        update saved_obj with changes from obj
    else:
        insert obj
    commit

But, such solution is kind of very ineffective.

I would rather select from time range, than compare time range of objects from table with time range objects from list (they don't have to match one to one), update objects that are changed, insert what's new and commit.

If someone has experience with such mass inserts/updates, please share your experiences, how to do that efficiently with sqlite and sqlalchemy ^= 1.4.

Aucun commentaire:

Enregistrer un commentaire