Insert or update peewee entry in python

Is there a simple one-line way to use it peeweein Python to either insert a record if the primary key does not already exist, or update the record if it already exists.

I am currently 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 could not see the create or update command, but maybe I missed something.

+4
source share
1 answer

Depends on the database. If you are using SQLite or MySQL, you can use the method upsert(): http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=upsert#InsertQuery.upsert

get_or_create: http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=get_or_create#Model.get_or_create

create_or_get, .

+8

Source: https://habr.com/ru/post/1614189/


All Articles