我的一个具有 ForeignKey
的模型实际上是其他表上的 MySQL View 。我遇到的问题是,当我从这些表中删除数据时,Django,如 "deleting objects" documentation 中所述...
When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.
...尝试从我的 View 中删除行,这当然不能,因此抛出错误:
mysql_exceptions.OperationalError '>=(1395, "Can not delete from join view 'my_db.my_mysql_view'"'
有没有什么方法可以在模型上指定一个 ForeignKey
约束,这将为我提供所有 Django 魔法,但不会级联删除到它?或者,有没有办法让 MySQL 忽略从我的 View 中删除行的命令,而不是引发错误?
最佳答案
Django 1.3a1及以上通过 ForeignKey
的 on_delete
支持此功能论据。
以下示例在删除外键时设置字段 NULL
。见 documentation更多选择。
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
关于mysql - 如何使用不级联删除其子项的外键创建 Django 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1006135/