I have a simple model with a generic foreign key:
class Generic(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
I would like to filter all entries in this table that have non-null content_object
's, i.e. filter out all instances of Generic
whose content objects no longer exist:
Generic.objects.filter(~Q(content_object=None))
This doesn't work, giving the exception:
django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation.
Adding GenericRelation
to the referenced content type models makes no difference.
Any help on how to achieve this would be appreciated, many thanks.
EDIT: I realise I could cascade the delete, however this is not an option in my situation (I wish to retain the data).
object_id
field is null, not the related object referenced by that id. Either way if you fix that it still gives the same exception as posted in the original question. Filter or exclude makes no difference here. FWIW checking= None
is the same asisnull=True
. – Emancipated