【问题标题】:Python peewee foreign key constraint incorrectly formedPython peewee 外键约束格式不正确
【发布时间】:2018-02-13 12:56:52
【问题描述】:


我目前正在使用 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 misformed")')

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

【问题讨论】:

    标签: python mysql peewee


    【解决方案1】:

    因此,在 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`)
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢你解决了我的表名问题,现在外键约束问题也消失了。我有一个旧项目的代码,我使用 peewee==2.xx。
    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 2021-11-07
    • 2018-09-04
    • 2017-10-03
    • 2019-07-25
    • 1970-01-01
    • 2017-10-04
    • 2018-06-19
    相关资源
    最近更新 更多