[英]Python peewee foreign key constraint incorrectly formed
我目前正在使用 peewee 連接到 MySQLDatabase 的 python 項目。
如果我想使用database.create_tables(tables=[])
創建一個表(create_table 不起作用)
我從我的記錄器中收到以下錯誤消息:
ERROR session[5924]: (1005, 'Can't create table example_database.example_table (errno: 150 "外鍵約束的格式不正確")')
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`)
希望有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.