python
data_error
ai_generated
true
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%Fix Rate
85%Confidence
0Evidence
2024-09-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Deleting a parent object that has child objects with on_delete=PROTECT.
generic中文
删除具有 on_delete=PROTECT 子对象的父对象。
Workarounds
-
95% success
Delete child objects first: Book.objects.filter(author=author).delete() then author.delete()
-
80% success
Change on_delete=models.CASCADE in model and run migrations to allow cascading delete.
Dead Ends
Common approaches that don't work:
-
60% fail
Changing on_delete to CASCADE in model requires migration and may delete data unintentionally.
-
50% fail
Using raw SQL DELETE ignores Django's protection and can cause orphaned records.