Search code examples
peewee

How do I update a field, if row exists, otherwise insert row?


Let's say I have the following data in my database:

k    c1    c2
0     1  null
1  null     1

Say I run a calculation which gives me a list of pairs (k, c1). I want to push these pairs into my database as follows:

  1. If k exists in my table, update c1 (leave c2 as is)
  2. If k does not exist in my table, add a new row with c2 set to null (or whatever the default value is for that column)

Is there a way to do this in a single operation, akin to

table.insert_many(rows)

?

table.inser_many doesn't work for me, as it forces c2 to null even if c2 used to have a value.


Solution

  • Depends on your database, but most of them (including recent versions of sqlite) support some flavor of upsert / insert on conflict update.

    http://docs.peewee-orm.com/en/latest/peewee/querying.html#upsert

    Consult your database docs for details on the specific implementation.