Insert or update a peewee record in python

kyrenia picture kyrenia · Nov 2, 2015 · Viewed 17.1k times · Source

Is there a simple one-line way using peewee in Python of either inserting a record if the primary key does not already exist, or updating the record if it does already exist.

Currently i am using the code:

try:
    sql_database.create(record_key = record_key, record_data_2 = record_data_2)
except IntegrityError:  ## Occurs if primary_key already exists
    sql_database.update(record_key = record_key, record_data_2 = record_data_2)

I couldn't see a "create or update" command, but maybe i am missing something.

Answer

coleifer picture coleifer · Nov 20, 2015

Depends on the database.

For SQLite and MySQL, peewee 3.x supports INSERT OR REPLACE. See docs: http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.replace

For Postgresql, peewee 3.x offers complete support of the ON CONFLICT clause. Note that you can use the "on_conflict" APIs with SQLite and MySQL -- the restriction is that they don't support the "UPDATE" action. See docs: http://docs.peewee-orm.com/en/latest/peewee/api.html#OnConflict

Examples:

# Works with SQLite and MySQL (which use "REPLACE")
result = (Emp
          .insert(first='mickey', last='dog', empno='1337')
          .on_conflict('replace')
          .execute())

# Works with Postgresql (which supports ON CONFLICT ... UPDATE).
result = (Emp
          .insert(first='foo', last='bar', empno='125')
          .on_conflict(
              conflict_target=(Emp.empno,),
              preserve=(Emp.first, Emp.last),
              update={Emp.empno: '125.1'})
          .execute())

You can also use the get_or_create method: http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=get_or_create#Model.get_or_create