[2.0.x] Fixed #28856 -- Fixed a regression in caching of a GenericForeignKey pointing to a MTI model.

Regression in b9f8635f58.

Modified backport of e50add6ca1 from master
This commit is contained in:
Simon Charette 2017-11-29 01:06:45 -05:00 committed by Tim Graham
parent 4d3b8e199e
commit d31424fec1
3 changed files with 19 additions and 5 deletions

View File

@ -228,12 +228,17 @@ class GenericForeignKey(FieldCacheMixin):
rel_obj = self.get_cached_value(instance, default=None)
if rel_obj is not None:
ct_match = ct_id == self.get_content_type(obj=rel_obj, using=instance._state.db).id
pk_match = rel_obj._meta.pk.to_python(pk_val) == rel_obj.pk
if ct_match and pk_match:
return rel_obj
else:
if ct_id != self.get_content_type(obj=rel_obj, using=instance._state.db).id:
rel_obj = None
else:
pk = rel_obj._meta.pk
# If the primary key is a remote field, use the referenced
# field's to_python().
pk_to_python = pk.target_field.to_python if pk.remote_field else pk.to_python
if pk_to_python(pk_val) != rel_obj._get_pk_val():
rel_obj = None
else:
return rel_obj
if ct_id is not None:
ct = self.get_content_type(id=ct_id, using=instance._state.db)
try:

View File

@ -27,3 +27,6 @@ Bugfixes
* Made query lookups for ``CICharField``, ``CIEmailField``, and ``CITextField``
use a ``citext`` cast (:ticket:`28702`).
* Fixed a regression in caching of a ``GenericForeignKey`` when the referenced
model instance uses multi-table inheritance (:ticket:`28856`).

View File

@ -48,6 +48,12 @@ class GenericRelationTests(TestCase):
TextLink.objects.create(content_object=oddrel)
oddrel.delete()
def test_coerce_object_id_remote_field_cache_persistence(self):
restaurant = Restaurant.objects.create()
CharLink.objects.create(content_object=restaurant)
charlink = CharLink.objects.latest('pk')
self.assertIs(charlink.content_object, charlink.content_object)
def test_q_object_or(self):
"""
SQL query parameters for generic relations are properly