Python peewee 外键约束的形成不正确

标签 python mysql peewee


我目前正在开发一个使用 peewee 连接到 MySQLDatabase 的 python 项目。
如果我想使用创建一个表 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 对象。
问题是,为什么外键约束不起作用以及为什么表都以小写形式保存,但我以大写形式定义它们

如果我再次运行该程序,它会创建表,但会出现重复的 key_name 错误

版本:peewee==3.0.17

最佳答案

因此,在 peewee 3.x 中,您使用 table_name 而不是 db_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'

我创建了表并检查了 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`)

希望有帮助。

关于Python peewee 外键约束的形成不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48767396/

相关文章:

python - 强制工作人员在启用持久交付模式时立即获取失败的消息

Python-创建虚拟环境时没有pip

php - 如何从数组中打印特定值?

python - Peewee 模型中的 getter 和 setter 方法

python - PeeWee PostgreSQL 数据库创建 : does not exist

javascript - 将更改付款方式设置为默认的 braintree drop-in ui

python - 在多线程生产者-消费者模式下,如何让工作线程在工作完成后退出?

php - 使用 PHP 计算在 MySQL 数据库中输入评级的次数

php - 选择 15 天前的记录

mysql - 使用 peewee 和 pymysql 设置 'charset=utf8' 时出现问题