简体   繁体   English

Python peewee 外键约束格式错误

[英]Python peewee foreign key constraint incorrectly formed


I'm currently working on a python project using peewee to connect to MySQLDatabase.我目前正在使用 peewee 连接到 MySQLDatabase 的 python 项目。
If I want to create a table using database.create_tables(tables=[]) (create_table does not work)如果我想使用database.create_tables(tables=[])创建一个表(create_table 不起作用)
I get the following error message from my logger:我从我的记录器中收到以下错误消息:

ERROR session[5924]: (1005, 'Can't create table example_database.example_table (errno: 150 "Foreign key constraint is incorrectly formed")') ERROR session[5924]: (1005, 'Can't create table example_database.example_table (errno: 150 "外键约束的格式不正确")')

example_table is specified as: example_table 指定为:

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

BaseModel is defined as follows: BaseModel 定义如下:

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

and database is my MySQLDatabase Object.和数据库是我的 MySQLDatabase 对象。
The Problem is, why doesnt the foreign key constraint work and why are the tables all saved in Lowercase, but I defined them in Uppercase问题是,为什么外键约束不起作用,为什么表都以小写形式保存,但我用大写形式定义了它们

If I run the program again, It creates the tables but gives me a duplicate key_name error如果我再次运行该程序,它会创建表但给我一个重复的 key_name 错误

Version: peewee==3.0.17版本:peewee==3.0.17

So, in peewee 3.x, you use table_name rather than db_table to explicitly declare a non-default table name.因此,在 peewee 3.x 中,您使用table_name而不是db_table来显式声明非默认表名。

I ran some sample code locally to give a test:我在本地运行了一些示例代码来进行测试:

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'

I created the tables and checked the SQL output, which looks correct to me:我创建了表并检查了 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`)

Hope that helps.希望有帮助。

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

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