Filter non-existent GenericForeignKey objects in a Django collection

I have a simple model with a shared 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 records in this table with non-zero content_object , i.e. filter out all instances Genericwhose content objects no longer exist

Generic.objects.filter(~Q(content_object=None))

This does not work, giving an exception:

django.core.exceptions.FieldError: the 'content_object' field does not generate an automatic inverse relation and therefore cannot be used for the reverse request. If it's a GenericForeignKey, consider adding a GenericRelation.

Adding GenericRelationto reference content types does not matter.

Any help on how to achieve this will be appreciated, thank you very much.

EDIT: , , ( ).

+4
1

, exclude():

Generic.objects.exclude(object_id__isnull=True)

, content_object. , null=True object_id content_type.

Update

, , ( ) :

broken_items = []
for ct in ContentType.objects.all():        
    broken_items.extend(
        Generic.objects
        .filter(content_type=ct)
        .exclude(object_id__in=ct.model_class().objects.all())
        .values_list('pk', flat=True))

script, . , , , - is_deleted Generic (post|pre)_delete.

+4

Source: https://habr.com/ru/post/1626024/


All Articles