Exclude null GenericForeignKey objects from Django query

712 views Asked by At

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.

1

There are 1 answers

2
Kevin Christopher Henry On BEST ANSWER

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.