I'm creating a reusable django app which includes a model with GenericForeignKey which I need to be cascade deleted.
This model may be attached to any other. I have no control over target model class as it is outside of the app. This means I can not add GenericRelation field to it and can't force user to add it as target might be in another third-party app.
Assuming we have such models (having NO control over Post and PostGroup):
class Tag(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
object = GenericForeignKey()
class PostGroup(models.Model):
title = models.CharField(max_length=255)
class Post(models.Model):
title = models.CharField(max_length=255)
group = models.ForeignKey(PostGroup, on_delete=models.CASCADE)
Is there a way to delete Tag in case of PostGroup queryset is being deleted?
E.g. not only post_group.delete() but also PostGroup.objects.delete().
You can use
pre_deletesignal to achieve this:See documentation here