python
data_error
ai_generated
true
删除保护错误:无法删除 'Author' 模型的某些实例,因为它们通过受保护的外键 'Book.author' 被引用
django.db.models.deletion.ProtectedError: Cannot delete some instances of model 'Author' because they are referenced through protected foreign keys: 'Book.author'
ID: python/django-foreign-key-delete-protection
80%修复率
85%置信度
0证据数
2024-09-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
删除具有 on_delete=PROTECT 子对象的父对象。
English
Deleting a parent object that has child objects with on_delete=PROTECT.
解决方案
-
95% 成功率
Delete child objects first: Book.objects.filter(author=author).delete() then author.delete()
-
80% 成功率
Change on_delete=models.CASCADE in model and run migrations to allow cascading delete.
无效尝试
常见但无效的做法:
-
60% 失败
Changing on_delete to CASCADE in model requires migration and may delete data unintentionally.
-
50% 失败
Using raw SQL DELETE ignores Django's protection and can cause orphaned records.