Skip to content

Commit d4456bd

Browse files
committed
Raise PolymorphicTypeInvalid when model is None
1 parent a89c153 commit d4456bd

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

polymorphic/models.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,17 +157,23 @@ def get_real_instance(self):
157157
retrieve objects, then the complete object with it's real class/type
158158
and all fields may be retrieved with this method.
159159
160-
If the model of the object's actual type does not exist (e.g. it was
161-
removed but its ContentType still exists), this method returns self.
160+
If the model of the object's actual type does not exist (i.e. its
161+
ContentType is stale), this method raises a
162+
:class:`~polymorphic.models.PolymorphicTypeInvalid` exception.
162163
163164
.. note::
164165
Each method call executes one db query (if necessary).
165166
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
166167
to upcast a complete list in a single efficient query.
167168
"""
168169
real_model = self.get_real_instance_class()
169-
if real_model == self.__class__ or real_model is None:
170+
if real_model == self.__class__:
170171
return self
172+
if real_model is None:
173+
raise PolymorphicTypeInvalid(
174+
f"ContentType {self.polymorphic_ctype_id} for {self.__class__} "
175+
f"#{self.pk} does not have a corresponding model!"
176+
)
171177
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
172178

173179
def __init__(self, *args, **kwargs):

polymorphic/tests/test_orm.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -321,12 +321,14 @@ def test_manual_get_real_instance(self):
321321
o = Model2A.objects.non_polymorphic().get(field1="C1")
322322
assert o.get_real_instance().__class__ == Model2C
323323

324-
def test_get_real_instance_with_no_model_class(self):
325-
ctype = ContentType.objects.create(app_label="tests", model="nonexisting")
324+
def test_get_real_instance_with_stale_content_type(self):
325+
ctype = ContentType.objects.create(app_label="tests", model="stale")
326326
o = Model2A.objects.create(field1="A1", polymorphic_ctype=ctype)
327327

328328
assert o.get_real_instance_class() is None
329-
assert o.get_real_instance().__class__ == Model2A
329+
match = "does not have a corresponding model"
330+
with pytest.raises(PolymorphicTypeInvalid, match=match):
331+
o.get_real_instance()
330332

331333
def test_non_polymorphic(self):
332334
self.create_model2abcd()

0 commit comments

Comments
 (0)