Python peewee save () not working as expected

I am inserting / updating objects to MySQL database using peewee ORM for Python. I have a model like this:

class Person(Model):
    person_id = CharField(primary_key=True)
    name = CharField()


I create objects / strings with a loop and every time through the loop there is a dictionary like:

pd = {"name":"Alice","person_id":"A123456"}


Then I try to create an object and save it.

po = Person()
for key,value in pd.items():


This takes some time to complete and works without error, but does not store anything in the database - no records are created.

It works:



But also throws an error (and terminates the script) when the primary key already exists. From the manual I read, I thought that save()

was the function I needed - that peewee would update or insert as needed.

Not sure what I need to do here - try getting each entry first? Catch errors and try to update the record if it can't be created? I am new to peewee and usually write INSERT ... ON DUPLICATE KEY UPDATE

or even REPLACE



source to share

3 answers

I had the opportunity to double-check my answer and I think it needs to be replaced. Here is a sample I can now recommend; first use the get_or_create () model which will create the database row if it doesn't exist. Then if it is not created (the object is fetched from db instead), set all the attributes from the data dictionary and save the object.

po, created = Person.get_or_create(person_id=pd["person_id"],defaults=pd)
if created is False:
    for key in pd:


As before, I must mention that these are two different transactions, so this should not be used with multi-user databases that require a genuine upsert in the same transaction.




He has documented:





All Articles