Skip to content

Check for None on real_model in get_real_instance #632

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions polymorphic/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ def get_real_instance(self):
retrieve objects, then the complete object with it's real class/type
and all fields may be retrieved with this method.

If the model of the object's actual type does not exist (i.e. its
ContentType is stale), this method raises a
:class:`~polymorphic.models.PolymorphicTypeInvalid` exception.

.. note::
Each method call executes one db query (if necessary).
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
Expand All @@ -165,6 +169,11 @@ def get_real_instance(self):
real_model = self.get_real_instance_class()
if real_model == self.__class__:
return self
if real_model is None:
raise PolymorphicTypeInvalid(
f"ContentType {self.polymorphic_ctype_id} for {self.__class__} "
f"#{self.pk} does not have a corresponding model!"
)
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)

def __init__(self, *args, **kwargs):
Expand Down
9 changes: 9 additions & 0 deletions polymorphic/tests/test_orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,15 @@ def test_manual_get_real_instance(self):
o = Model2A.objects.non_polymorphic().get(field1="C1")
assert o.get_real_instance().__class__ == Model2C

def test_get_real_instance_with_stale_content_type(self):
ctype = ContentType.objects.create(app_label="tests", model="stale")
o = Model2A.objects.create(field1="A1", polymorphic_ctype=ctype)

assert o.get_real_instance_class() is None
match = "does not have a corresponding model"
with pytest.raises(PolymorphicTypeInvalid, match=match):
o.get_real_instance()

def test_non_polymorphic(self):
self.create_model2abcd()

Expand Down