Fix database casting issue
This commit is contained in:
parent
fd1efc8dfa
commit
b387089be4
|
@ -24,6 +24,28 @@ except AttributeError: # Django < 2.0.
|
|||
pass
|
||||
|
||||
|
||||
def get_pk_output_field(model):
|
||||
"""Gets an instance of the field type for the primary key of the given model, useful for database CAST."""
|
||||
pk = model._meta.pk
|
||||
field_cls = type(pk)
|
||||
field_kwargs = {}
|
||||
if isinstance(pk, models.CharField):
|
||||
# Some versions of Django produce invalid SQL for the CAST function (in some databases)
|
||||
# if CharField does not have max_length passed.
|
||||
# Therefore, it is necessary to copy over the max_length of the original field to avoid errors.
|
||||
# See: https://code.djangoproject.com/ticket/28371
|
||||
field_kwargs['max_length'] = pk.max_length
|
||||
elif isinstance(pk, models.AutoField):
|
||||
# Some versions of Django appear to also produce invalid SQL in MySQL
|
||||
# when attempting to CAST with AutoField types.
|
||||
# This covers for that by instead casting to the corresponding integer type.
|
||||
if isinstance(pk, models.BigAutoField):
|
||||
field_cls = models.BigIntegerField
|
||||
else:
|
||||
field_cls = models.IntegerField
|
||||
return field_cls(**field_kwargs)
|
||||
|
||||
|
||||
def has_int_pk(model):
|
||||
"""Tests whether the given model has an integer primary key."""
|
||||
pk = model._meta.pk
|
||||
|
|
|
@ -446,13 +446,12 @@ 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, has_int_pk, get_pk_output_field
|
||||
content_type = ContentType.objects.get_for_model(model)
|
||||
id_output_field = type(model._meta.pk)
|
||||
object_id_field = 'object_id_int' if has_int_pk(model) else 'object_id'
|
||||
return SearchEntry.objects.annotate(
|
||||
# normalize the object id into a field of the correct type for the original table
|
||||
normalized_pk=Cast(object_id_field, id_output_field())
|
||||
normalized_pk=Cast(object_id_field, get_pk_output_field(model))
|
||||
).filter(
|
||||
Q(content_type=content_type) &
|
||||
Q(engine_slug=self._engine_slug) &
|
||||
|
|
Loading…
Reference in New Issue