推荐学习书目
› 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 · Feb 13, 2017 · 6516 views
    This topic created in 3511 days ago, the information mentioned may be changed or developed.

    有个疑惑, 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 replies  •  2017-02-14 21:15:13 +08:00
    glasslion
        1
    glasslion  
       Feb 13, 2017
    连文档都不读吗?

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

    是在应用层做的 ON DELETE CASCADE, 不是 db 层
    xueqt
        4
    xueqt  
    OP
       Feb 14, 2017
    @glasslion 谢谢,我再看看
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2400 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 133ms · UTC 11:41 · PVG 19:41 · LAX 04:41 · JFK 07:41
    ♥ Do have faith in what you're doing.