V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
xueqt
V2EX  ›  Python

django on_delete 级联删除不生效么?

  •  
  •   xueqt · 2017-02-13 16:43:23 +08:00 · 5292 次点击
    这是一个创建于 2630 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有个疑惑, 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 属性有什么意义呢。

    4 条回复    2017-02-14 21:15:13 +08:00
    glasslion
        1
    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
        2
    xueqt  
    OP
       2017-02-14 13:00:15 +08:00
    @glasslion 我意思是设置 on_delete 为 CASCADE, 并未生效,到数据库查看表的属性并没有相应地改变。我看网上也有类似的疑问,但官方文档上写着是支持 CASCADE 的,所以过来问下。
    glasslion
        3
    glasslion  
       2017-02-14 13:15:23 +08:00
    @xueqt Django **emulates** the behavior of

    是在应用层做的 ON DELETE CASCADE, 不是 db 层
    xueqt
        4
    xueqt  
    OP
       2017-02-14 21:15:13 +08:00
    @glasslion 谢谢,我再看看
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5365 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:34 · PVG 15:34 · LAX 00:34 · JFK 03:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.