Cast object id lookup to pk field type

This commit is contained in:
Cristopher Hernandez 2021-10-24 16:54:29 -07:00 committed by Guillaume Baffoin
parent 1966298468
commit cd358f4749
1 changed files with 13 additions and 12 deletions

View File

@ -15,6 +15,7 @@ from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.db import models, connections, router
from django.db.models import Q
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce
from django.db.models.query import QuerySet
from django.db.models.signals import post_save, pre_delete
from django.utils.encoding import force_str
@ -445,21 +446,21 @@ class SearchEngine(object):
def _get_deleted_entries_for_model(self, model):
"""Returns a queryset of entries associated with deleted object instances of the given model"""
from django.contrib.contenttypes.models import ContentType
from watson.models import SearchEntry, has_int_pk
from watson.models import SearchEntry
content_type = ContentType.objects.get_for_model(model)
# subquery to get entries which cannot be found in the original table (when negated)
lookup_subquery = models.Subquery(
model.objects.all().values('pk')
)
# map the lookup to the appropriate id field
if has_int_pk(model):
id_lookup = {'object_id_int__in': lookup_subquery}
else:
id_lookup = {'object_id__in': lookup_subquery}
return SearchEntry.objects.filter(
id_output_field = type(model._meta.pk)
return SearchEntry.objects.annotate(
# normalize the object id into a single field of the correct type
normalized_pk=Coalesce('object_id_int', 'object_id', output_field=id_output_field())
).filter(
Q(content_type=content_type) &
Q(engine_slug=self._engine_slug) &
~Q(**id_lookup)
# subquery to get entries which cannot be found in the original table (when negated)
~Q(
normalized_pk__in=models.Subquery(
model.objects.all().values('pk')
)
)
)
def _get_entries_for_obj(self, obj):