Opened 3 weeks ago

Closed 11 days ago

Last modified 11 days ago

#37471 closed Bug (fixed)

No system check for GenericRelation on a model with DB_CASCADE, leaving orphaned generic rows

Reported by: Akshat Gupta Owned by: Akshat Gupta
Component: Database layer (models, ORM) Version: 6.1
Severity: Release blocker Keywords: DB_CASCADE, GenericRelation, on_delete
Cc: Akshat Gupta Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The docs say that database-level and Python-level on_delete variants cannot be mixed in the same model or in related models. System checks enforce this with models.E050 and fields.E323.

GenericRelation is a Python-level cleanup, but it is not checked. If a model has a GenericRelation and a DB_CASCADE foreign key, the database deletes the model's rows and Django never deletes the generic related objects. They stay in the table with no error and no check warning.

class Tag(models.Model):
    content_type = models.ForeignKey(ContentType, models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()


class Author(models.Model):
    pass


class Book(models.Model):
    author = models.ForeignKey(Author, models.DB_CASCADE)
    tags = GenericRelation(Tag)
>>> author = Author.objects.create()
>>> book = Book.objects.create(author=author)
>>> book.tags.create()
>>> author.delete()
>>> Book.objects.count(), Tag.objects.count()
(0, 1)

manage.py check reports no issues. With models.CASCADE instead of models.DB_CASCADE, the Tag row is deleted.

Why it happens: Collector.collect() skips DB_CASCADE relations, so Book instances are never collected. Their private fields are never visited, so GenericRelation.bulk_related_objects() never runs. GenericRelation.remote_field.on_delete is DO_NOTHING, so Model._check_related_fields() does not see it as a Python-level variant.

I verified this on 6.1.3 and on main with SQLite. I also ran random schemas with database and Python on_delete variants against the equivalent all-Python schemas. Among schemas that pass all checks, the only difference in the final data was orphaned generic rows.

Suggested fix: add a system check error for a model that has a GenericRelation (any private field with bulk_related_objects()) and a DB_CASCADE foreign key. It would not fire for DB_SET_NULL or DB_SET_DEFAULT, because those do not delete the model's rows. This is the same kind of gap as #37254 (implicit M2M through tables), which was fixed in 6.1.x.

I am happy to work on a patch once the approach is agreed.

Change History (6)

comment:1 by Sarah Boyce, 3 weeks ago

Severity: Normal → Release blocker
Triage Stage: Unreviewed → Accepted

Thank you for the report
Confirmed with the test below (the final exists() returns True, so the generic related object survives the database cascade).

Personally I think that a system check should flag this combination similar to #37254. Perhaps we could reuse models.E050 with a hint such as “Generic relations use Python-level cascading.”?

  • tests/generic_relations/models.py

    a b class AllowsNullGFK(models.Model):  
    150150    content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True)
    151151    object_id = models.PositiveIntegerField(null=True)
    152152    content_object = GenericForeignKey()
     153
     154
     155class DatabaseCascade(models.Model):
     156    mineral = models.ForeignKey(Mineral, models.DB_CASCADE)
     157    tags = GenericRelation(TaggedItem)
  • tests/generic_relations/tests.py

    diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py
    index 99832eca3e..68ad3af5d1 100644
    a b from .models import (  
    1111    Carrot,
    1212    Comparison,
    1313    ConcreteRelatedModel,
     14    DatabaseCascade,
    1415    ForConcreteModelModel,
    1516    ForProxyModelModel,
    1617    Gecko,
    … … class GenericRelationsTests(TestCase):  
    850851        tag = tags[0]
    851852        self.assertEqual(tag._state.fetch_mode, FETCH_PEERS)
    852853
     854    def test_database_cascade_deletes_generic_related_objects(self):
     855        quartz = Mineral.objects.create(name="Quartz", hardness=7)
     856        obj = DatabaseCascade.objects.create(mineral=quartz)
     857        tag = book.tags.create()
     858
     859        quartz.delete()
     860
     861        self.assertFalse(
     862            DatabaseCascade.objects.filter(pk=obj.pk).exists()
     863        )
     864        self.assertFalse(
     865            TaggedItem.objects.filter(pk=tag.pk).exists()
     866        )
     867
    853868
    854869class ProxyRelatedModelTest(TestCase):

comment:3 by Akshat Gupta, 3 weeks ago

Owner: set to Akshat Gupta
Status: new → assigned

comment:4 by Sarah Boyce, 12 days ago

Triage Stage: Accepted → Ready for checkin

comment:5 by Sarah Boyce <42296566+sarahboyce@…>, 11 days ago

Resolution: → fixed
Status: assigned → closed

In 5d6d1f0:

Fixed #37471 -- Made models.E050 detect generic relations with database-level on_delete.

comment:6 by Sarah Boyce <42296566+sarahboyce@…>, 11 days ago

In 635a05c1:

[6.1.x] Fixed #37471 -- Made models.E050 detect generic relations with database-level on_delete.

Backport of 5d6d1f051e0930537b8eda9760d05441d4279594 from main.

Note: See TracTickets for help on using tickets.
Back to Top