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():
    setattr(po,key,value)
po.save()

      

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

It works:

Person.create(**pd)

      

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

.

+3


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:
        setattr(fa,key,pd[key])
    po.save()

      



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.

+1


source


Person.save(force_insert=True)

      



He has documented: http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks

+5


source


0


source







All Articles