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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Deleting a parent object that has child objects with on_delete=PROTECT.

generic

中文

删除具有 on_delete=PROTECT 子对象的父对象。

Workarounds

  1. 95% success
    Delete child objects first: Book.objects.filter(author=author).delete() then author.delete()
  2. 80% success
    Change on_delete=models.CASCADE in model and run migrations to allow cascading delete.

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Changing on_delete to CASCADE in model requires migration and may delete data unintentionally.

  2. 50% fail

    Using raw SQL DELETE ignores Django's protection and can cause orphaned records.