From eb128ceb849f81e190d87e81b9630fdbaa852666 Mon Sep 17 00:00:00 2001 From: Cristopher Hernandez <22552070+CristopherH95@users.noreply.github.com> Date: Sun, 24 Oct 2021 16:54:29 -0700 Subject: [PATCH] Cast object id lookup to pk field type --- watson/search.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/watson/search.py b/watson/search.py index 7d1a7b6..a1f6b02 100644 --- a/watson/search.py +++ b/watson/search.py @@ -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):