Search code examples
djangoforeign-keyscascading-deletesdjango-contenttypesgeneric-foreign-key

Why won't my GenericForeignKey cascade when deleting?


I'm creating a custom commenting system which can attache comments to any model using the contenttypes GenericForeignKey.

class Comment(models.Model):
    body = models.TextField(verbose_name='Comment')
    user = models.ForeignKey(User)
    parent = models.ForeignKey('self', null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

It is my understanding that when the model the comment is attached to is deleted, the delete should cascade and remove the comment as well.

Unfortunately, this isn't happening and I'm stumped. Are there any common reasons why the default delete behaviour would change?


Solution

  • No, the documentation doesn't say that. What it says is that if you define a GenericRelation on a model - ie the reverse side of the GenericForeignKey - then when the item with the generic FK is deleted, the item with the GenericRelation will also be deleted.

    Unlike ForeignKey, GenericForeignKey does not accept an on_delete argument to customize this behavior; if desired, you can avoid the cascade-deletion simply by not using GenericRelation, and alternate behavior can be provided via the pre_delete signal.