#36428: Collector.delete() calls sort() but does not order deletions correctly
when
nullable FK is present with non-null value
-------------------------------------+-------------------------------------
Reporter: Andréas Kühne | Type: Bug
Status: new | Component: Database
| layer (models, ORM)
Version: 5.1 | Severity: Normal
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
When using DeleteView or Model.delete() in Django 5.1.8, I encountered a
IntegrityError from PostgreSQL. The issue stems from the deletion order of
models: Django attempts to delete a parent (ActivityLocation) before its
dependent child (BookableItem), despite on_delete=models.CASCADE being
set.
This occurs even though the Collector calls .sort(), which is supposed to
reorder models in dependency-safe order. The BookableItem.location FK is
nullable (null=True), but the actual instance has a non-null FK set.
Models to reproduce:
{{{
from django.db import models
class ActivityLocation(models.Model):
name = models.CharField(max_length=100)
class BookableItem(models.Model):
name = models.CharField(max_length=100)
location = models.ForeignKey(
ActivityLocation,
on_delete=models.CASCADE,
related_name='bookable_items',
null=True,
blank=True,
)
}}}
Steps to reproduce:
{{{
# Create parent and child
location = ActivityLocation.objects.create(name="Test Location")
item = BookableItem.objects.create(name="Test Item", location=location)
# Try to delete the location
location.delete()
}}}
What I think should happen:
BookableItem should be deleted before ActivityLocation, as Django is
responsible for enforcing deletion order (Postgres won’t do it
automatically with deferred constraints).
What actually happens:
Django runs Collector.delete() which internally calls sort(), but the
model deletion order remains:
{{{
[ActivityLocation, BookableItem]
}}}
If I however change to this:
{{{
from django.db import models
class BookableItem(models.Model):
name = models.CharField(max_length=100)
location = models.ForeignKey(
ActivityLocation,
on_delete=models.CASCADE,
related_name='bookable_items',
)
}}}
Then the code works as expected.
--
Ticket URL: <https://code.djangoproject.com/ticket/36428>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/django-updates/010701973128ca86-3c52344b-6a06-4821-bb7d-1b689426f789-000000%40eu-central-1.amazonses.com.