2👍
✅
That’s because there can in fact be duplicate ids in the GenericForeignKey
. E.g. if you have a Photo
model and an Article
model, both with an Entry
associated with it, the photo’s primary key can be the same value as the article’s primary key, and the object_id
s will be the same. That’s why you need both a content_type
and an object_id
to begin with.
To get the right object, you need to check for both the type and id.
from django.contrib.contenttypes.models import ContentType
def delete_entry(sender, instance, **kwargs):
content_type = ContentType.objects.get_for_model(instance)
entry = Entry.objects.get(content_type=content_type,
object_id=instance.id)
entry.delete()
Another way to accomplish this is to use a GenericRelation
(see documentation). This is the reverse relation of a GenericForeignKey
. Whenever an object with a GenericRelation
is deleted, this cascades to any objects of the supplied model with a GenericForeignKey
pointing to that instance:
from django.contrib.contenttypes.generic import GenericRelation
class Photo(models.Model):
...
entries = GenericRelation(Entry, content_type_field='content_type',
object_id_field='object_id')
👤knbk
Source:stackexchange.com