I have the following model in my app, using the content-type django framework :
class GenericMedia(models.Model):
limit = models.Q(model = 'Image') | models.Q(model = 'Video') | models.Q(model = 'Other')
content_type = models.ForeignKey(ContentType, limit_choices_to = limit)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return u"%s" % os.path.basename(self.content_object.url.name)
def instance(self):
return self.content_object.__class__.__name__
class Media(models.Model):
description = models.CharField(blank = True, max_length = 500)
link = models.URLField(blank = True)
genericFK = generic.GenericRelation(GenericMedia, content_type_field='content_type', object_id_field='object_id')
class Meta:
abstract = True
def __unicode__(self):
return u"%s" % os.path.basename(self.url.name)
def save(self, *args, **kwargs):
super(Media, self).save(*args, **kwargs)
generic_link = GenericMedia(content_object = self)
generic_link.save()
class Image(Media):
imgW = models.PositiveSmallIntegerField()
imgH = models.PositiveSmallIntegerField()
url = models.ImageField(upload_to = 'mediamanager', height_field = 'imgH', width_field = 'imgW')
Everythings works fine, excepts the GenericRelation in my abstract Media Class. In django documentation it is said that :
If you delete an object that has a GenericRelation, any objects which have a GenericForeignKey pointing at it will be deleted as well.
But my problem is that when I delete an image, the GenericMedia pointing to it is not deleted.
If anyone has a solution, thanks !
As you mentioned it, the documentation is clear about what happens when you delete an object that has a Generic Relation field (Django deletes all objects that have a foreign key to the object with GenericRelation).
So this is basically Django's fault (probably some problem with the abstract classes), BUT there is a way to overcome this situation.
By using
pre_delete
you can delete all objects that have a foreign key to the object with GenericRelation.Some examples of
pre_delete
signal can be found here: http://www.koopman.me/2015/01/django-signals-example/