1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

Fixed #16281 -- Fixed ContentType.get_object_for_this_type() in a multiple database setup.

This commit is contained in:
Ben Cail
2023-11-15 14:32:03 -05:00
committed by Mariusz Felisiak
parent a47de0d6cd
commit 02a600ff67
6 changed files with 97 additions and 6 deletions

View File

@@ -280,7 +280,9 @@ class GenericForeignKey(FieldCacheMixin):
if ct_id is not None:
ct = self.get_content_type(id=ct_id, using=instance._state.db)
try:
rel_obj = ct.get_object_for_this_type(pk=pk_val)
rel_obj = ct.get_object_for_this_type(
using=instance._state.db, pk=pk_val
)
except ObjectDoesNotExist:
pass
self.set_cached_value(instance, rel_obj)

View File

@@ -174,20 +174,20 @@ class ContentType(models.Model):
except LookupError:
return None
def get_object_for_this_type(self, **kwargs):
def get_object_for_this_type(self, using=None, **kwargs):
"""
Return an object of this type for the keyword arguments given.
Basically, this is a proxy around this object_type's get_object() model
method. The ObjectNotExist exception, if thrown, will not be caught,
so code that calls this method should catch it.
"""
return self.model_class()._base_manager.using(self._state.db).get(**kwargs)
return self.model_class()._base_manager.using(using).get(**kwargs)
def get_all_objects_for_this_type(self, **kwargs):
"""
Return all objects of this type for the keyword arguments given.
"""
return self.model_class()._base_manager.using(self._state.db).filter(**kwargs)
return self.model_class()._base_manager.filter(**kwargs)
def natural_key(self):
return (self.app_label, self.model)