Python peewee 外键约束形成不正确

Python peewee foreign key constraint incorrectly formed


我目前正在开发一个 python 项目,使用 peewee 连接到 MySQLDatabase。
如果我想创建一个 table 使用 database.create_tables(tables=[])(create_table 不起作用)
我从记录器收到以下错误消息:

ERROR session[5924]: (1005, 'Can't create table example_database.example_table (errno: 150 "Foreign key constraint is incorrectly formed")')

example_table 指定为:

class Example_Table(BaseModel):
    id = PrimaryKeyField()
    example_table2 = ForeignKeyField(Modul)
    class Meta:
        db_table = 'Example_Table'

BaseModel定义如下:

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

数据库是我的 MySQLDatabase 对象。
问题是,为什么外键约束不起作用,为什么 table 都保存为小写,但我将它们定义为大写

如果我再次 运行 程序,它会创建 tables 但会给我一个重复的 key_name 错误

版本:peewee==3.0.17

因此,在 peewee 3.x 中,您使用 table_name 而不是 db_table 来显式声明非默认 table 名称。

我运行一些示例代码在本地进行测试:

class User(Model):
    username = TextField()
    class Meta:
        database = db
        table_name = 'UserTbl'

class Note(Model):
    user = ForeignKeyField(User, backref='notes')
    content = TextField()
    class Meta:
        database = db
        table_name = 'NoteTbl'

我创建了 tables 并检查了 SQL 输出,这对我来说是正确的:

CREATE TABLE IF NOT EXISTS `UserTbl` (`id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `username` TEXT NOT NULL)
CREATE TABLE IF NOT EXISTS `NoteTbl` (`id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` INTEGER NOT NULL, `content` TEXT NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `UserTbl` (`id`))
CREATE INDEX `note_user_id` ON `NoteTbl` (`user_id`)

希望对您有所帮助。