Skip to content

Commit a89c153

Browse files
committed
Check for None on real_model in get_real_instance
1 parent 3a81c0e commit a89c153

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

polymorphic/models.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,16 @@ 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.
162+
160163
.. note::
161164
Each method call executes one db query (if necessary).
162165
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
163166
to upcast a complete list in a single efficient query.
164167
"""
165168
real_model = self.get_real_instance_class()
166-
if real_model == self.__class__:
169+
if real_model == self.__class__ or real_model is None:
167170
return self
168171
return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
169172

polymorphic/tests/test_orm.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,13 @@ 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")
326+
o = Model2A.objects.create(field1="A1", polymorphic_ctype=ctype)
327+
328+
assert o.get_real_instance_class() is None
329+
assert o.get_real_instance().__class__ == Model2A
330+
324331
def test_non_polymorphic(self):
325332
self.create_model2abcd()
326333

0 commit comments

Comments
 (0)