Question

I have an ActivityLog Django Model that defines a generic foreign key with the following fields:

model_type = models.ForeignKey(ContentType, verbose_name=_("Object type"))
object_id = models.PositiveIntegerField(_("Object id"))
object = generic.GenericForeignKey('model_type', 'object_id')

I need to filter the ActivityLog instances whose related object has not been deleted (is not None). Django doesn't do an on delete cascade in GenericForeignKey and I need to exclude this undesired records from the lookup. Is there an easy, standard and efficient way to do this?

In a wonderful world I'd use something like:

real_activity_logs = ActivityLog.objects.filter(object__isnull=False)

But this doesn't work as object is not a database field.

Was it helpful?

Solution

If you want those ActivityLog instances to be deleted in a cascade, you can make that happen by defining a GenericRelation on the objects pointed to. From the documentation:

Note also, that if you delete an object that has a GenericRelation, any objects which have a GenericForeignKey pointing at it will be deleted as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top