Python peewee save() doesn't work as expected

ⅰ亾dé卋堺 提交于 2019-12-10 15:16:42

问题


I'm inserting/updating objects into a MySQL database using the peewee ORM for Python. I have a model like this:

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

I create the objects/rows with a loop, and each time through the loop have a dictionary like:

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

Then I try creating an object and saving it.

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

This takes a while to execute, and runs without errors, but it doesn't save anything to the database -- no records are created.

This works:

Person.create(**pd)

But also throws an error (and terminates the script) when the primary key already exists. From reading the manual, I thought save() was the function I needed -- that peewee would perform the update or insert as required.

Not sure what I need to do here -- try getting each record first? Catch errors and try updating a record if it can't be created? I'm new to peewee, and would normally just write INSERT ... ON DUPLICATE KEY UPDATE or even REPLACE.


回答1:


Person.save(force_insert=True)

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




回答2:


I've had a chance to re-test my answer, and I think it should be replaced. Here's the pattern I can now recommend; first, use get_or_create() on the model, which will create the database row if it doesn't exist. Then, if it is not created (object is retrieved 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 should mention that these are two distinct transactions, so this should not be used with multi-user databases requiring a true upsert in one transaction.




回答3:


I think you might try get_or_create()? http://peewee.readthedocs.org/en/latest/peewee/querying.html#get-or-create



来源:https://stackoverflow.com/questions/30038185/python-peewee-save-doesnt-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!