简体   繁体   English

新创建的 save() 上的 peewee 错误

[英]peewee error on newly created save()

Making myself familiar with peewee, I stumbled upon the following weird behavior: Given a class similar to this让自己熟悉 peewee,我偶然发现了以下奇怪的行为:给定一个类似于 this 的类

class Test(BaseModel):
    str = CharField(primary_key=True)

executing执行

instance = Test(str = 'something')
instance.save()

gives an obscure error complaining about some 'WHERE':给出一个模糊的错误,抱怨一些“WHERE”:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 3830, in execute_sql
    cursor.execute(sql, params or ())
sqlite3.OperationalError: near "WHERE": syntax error

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 5165, in save
    rows = self.update(**field_dict).where(self._pk_expr()).execute()
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 3458, in execute
    return self.database.rows_affected(self._execute())
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 2939, in _execute
    return self.database.execute_sql(sql, params, self.require_commit)
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 3837, in execute_sql
    self.commit()
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 3656, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 135, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 3830, in execute_sql
    cursor.execute(sql, params or ())
peewee.OperationalError: near "WHERE": syntax error

However, directly creating the instance using但是,直接使用创建实例

instance = Test.create(str = 'something')

works as expected.按预期工作。 This only seems to happen when the attribute used is a primary key.这似乎只在使用的属性是主键时发生。 A similar issue seems to be this question where no error is produced, but no database entry either.类似的问题似乎是这个问题,没有产生错误,但也没有数据库条目。 I'm aware of the workaround from the solution but just curious about this strange behavior.我知道解决方案中的解决方法,但只是对这种奇怪的行为感到好奇。

You need to use save(force_insert=True) when using a non-auto-incrementing primary key.使用非自增主键时需要使用save(force_insert=True)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM