python - on_delete ='CASCADE' 好像没有效果

标签 python peewee

我在两个模型之间建立了多对多关系,UserRole,通过中间表 UserRoleThrough 实现,它有两个 ForeignKeyField:一个引用 User,另一个引用 Role。据我从文档中了解到,ON DELETE通过使用 on_delete 参数初始化 ForeignKeyField 来支持功能。虽然不是很清楚 on_delete 可以取什么值,documentation举个例子,例如“级联”。这就是说,on_delete='CASCADE' 似乎没有效果,因为尝试从其中一个父表中删除一行会引发错误。

peewee.IntegrityError: FOREIGN KEY constraint failed

使用数据库浏览器检查生成的模式显示外键未使用 ON DELETE 声明。

CREATE TABLE "userrolethrough" (
    "id" INTEGER NOT NULL PRIMARY KEY,
    "user_id" INTEGER NOT NULL,
    "role_id" INTEGER NOT NULL,
     FOREIGN KEY ("user_id") REFERENCES "user" ("id"),
     FOREIGN KEY ("role_id") REFERENCES "role" ("id")
)

那么我这里做错了什么?如何让 on_delete 工作?这是使用 Python 3.6 和 Peewee 3.0.2 的最小可重现示例。

import peewee

db_proxy = peewee.Proxy()

class BaseModel(peewee.Model):
    class Meta:
        database = db_proxy

class User(BaseModel):
    name = peewee.CharField()

class Role(BaseModel):
    name = peewee.CharField()

class UserRoleThrough(BaseModel):
    user = peewee.ForeignKeyField(User, on_delete='CASCADE')
    role = peewee.ForeignKeyField(Role, on_delete='CASCADE')


if __name__ == '__main__':
    db = peewee.SqliteDatabase('test.db')
    db.pragma('foreign_keys', 1, permanent=True)
    db_proxy.initialize(db)

    tables = [
        User,
        Role,
        UserRoleThrough
    ]
    db.create_tables(tables)

    isaac = User.create(name='Isaac')
    admin = Role.create(name='Admin')
    UserRoleThrough.create(user=isaac, role=admin)
    User.delete().execute()

最佳答案

这在 3.0.6 中已修复:github.com/coleifer/peewee/blob/master/CHANGELOG.md#306

关于python - on_delete ='CASCADE' 好像没有效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48776346/

相关文章:

python - Python 中数据透视表列之间的差异

python - 在peewee中设置严格的sql模式

python - 如何在 Jupyter Notebook 或 JupyterLab 中使用破折号?

flask - 无法像 flask-peewee 的教程那样成功

python - 如何在Python代码中比较peewee日期

python - 使用 peewee 合并具有不同名称的字段

python - Peewee ORM 中的 before_save() 和 after_save() Hook ?

python - ImportError : this is MySQLdb version (1, 2, 4, 'beta' , 4), 但_mysql 是版本 (1, 2, 5, 'final' , 1)

python - 改进 Python 比较和存在操作

python - 成员函数装饰器和 self 参数