SQL Peewee 示例中的主键语法错误

SQL syntax error in Peewee example with primary key

我有一个遵循 quickstart tutorial 的简单 Peewee 数据库模型,我正在尝试向数据库添加一个实例。 returns 错误,

'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'WHERE (image.url = \'foo\')\' at line 1'

我把代码尽可能地配对了,但我找不到我的错误。这是我的模型的一个最小且可重现的(我希望它能在我的机器上重现)示例。编辑 MySQLDatabase 调用以适合您的设置。我从一个名为 'test'.

的空数据库开始
from peewee import *

database = MySQLDatabase('test', **{'password': '1234', 'user': 'root'})

class BaseModel(Model):
    class Meta:
        database = database

class Image(BaseModel):
    url = CharField(primary_key=True)

database.connect()
database.create_tables([Image])

image_url = 'foo'
image_entry = Image(url=image_url)
image_entry.save()

示例代码的最后一行抛出错误。如果查看我的数据库,我可以看到 table 'image' 已成功创建。

describe image;

returns

+-------+--------------+------+-----+---------+-------+  
| Field | Type         | Null | Key | Default | Extra |  
+-------+--------------+------+-----+---------+-------+  
| url   | varchar(255) | NO   | PRI | NULL    |       |  
+-------+--------------+------+-----+---------+-------+  

table 仍然如预期的那样是空的,因为错误是在保存语句期间出现的。

select * from image:

returns

Empty set(0.00 sec)

这可能对您有帮助:

https://peewee.readthedocs.org/en/2.0.2/peewee/fields.html#non-integer-primary-keys

from peewee import Model, PrimaryKeyField, VarCharColumn

class UUIDModel(Model):
    # explicitly declare a primary key field, and specify the class to use
    id = CharField(primary_key=True)

Auto-increment IDs are, as their name says, automatically generated for you when you insert a new row into the database. The way peewee determines whether to do an INSERT versus an UPDATE comes down to checking whether the primary key value is None. If None, it will do an insert, otherwise it does an update on the existing value. Since, with our uuid example, the database driver won’t generate a new ID, we need to specify it manually. When we call save() for the first time, pass in force_insert = True:

inst = UUIDModel(id=str(uuid.uuid4()))
inst.save() # <-- WRONG!!  this will try to do an update

inst.save(force_insert=True) # <-- CORRECT

# to update the instance after it has been saved once
inst.save()