Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert or update a peewee record in python

Tags:

python

peewee

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.

like image 739
kyrenia Avatar asked Nov 02 '15 19:11

kyrenia


1 Answers

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 and SQLite 3.24 and newer, peewee 3.x offers complete support of the ON CONFLICT clause. Note that you can use the "on_conflict" APIs with MySQL -- the restriction is that it doesn't support the "UPDATE" action. See docs: http://docs.peewee-orm.com/en/latest/peewee/api.html#OnConflict

Examples:

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

# Works with Postgresql and SQLite (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

like image 150
coleifer Avatar answered Oct 14 '22 11:10

coleifer