django on_delete 级联删除不生效么?

2017-02-13 16:43:23 +08:00
 xueqt

有个疑惑, django 设置 on_delete =models.CASCADE 好像没作用

class User(models.Model): email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) create_time = models.DateTimeField(auto_now_add=True)

class Session(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) token = models.CharField(max_length=100, unique=True)

数据库是 mysql ,默认引擎 innodb, migrate 之后并没有看到对应的表有设置 ON DELETE 属性 而且我如果先删除主表会提示 error ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails 另外, django 也不支持 on_update ?

我试着进数据库手动添加了 ON DELETE   CASCADE ,是可以的 那么, models 的这个 on_delete 属性有什么意义呢。

5298 次点击
所在节点    Python
4 条回复
glasslion
2017-02-13 17:00:17 +08:00
连文档都不读吗?

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey
xueqt
2017-02-14 13:00:15 +08:00
@glasslion 我意思是设置 on_delete 为 CASCADE, 并未生效,到数据库查看表的属性并没有相应地改变。我看网上也有类似的疑问,但官方文档上写着是支持 CASCADE 的,所以过来问下。
glasslion
2017-02-14 13:15:23 +08:00
@xueqt Django **emulates** the behavior of

是在应用层做的 ON DELETE CASCADE, 不是 db 层
xueqt
2017-02-14 21:15:13 +08:00
@glasslion 谢谢,我再看看

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/340175

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX