File tree Expand file tree Collapse file tree 2 files changed +18
-0
lines changed Expand file tree Collapse file tree 2 files changed +18
-0
lines changed Original file line number Diff line number Diff line change @@ -157,6 +157,10 @@ def get_real_instance(self):
157
157
retrieve objects, then the complete object with it's real class/type
158
158
and all fields may be retrieved with this method.
159
159
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.
163
+
160
164
.. note::
161
165
Each method call executes one db query (if necessary).
162
166
Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
@@ -165,6 +169,11 @@ def get_real_instance(self):
165
169
real_model = self .get_real_instance_class ()
166
170
if real_model == self .__class__ :
167
171
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
+ )
168
177
return real_model .objects .db_manager (self ._state .db ).get (pk = self .pk )
169
178
170
179
def __init__ (self , * args , ** kwargs ):
Original file line number Diff line number Diff line change @@ -321,6 +321,15 @@ def test_manual_get_real_instance(self):
321
321
o = Model2A .objects .non_polymorphic ().get (field1 = "C1" )
322
322
assert o .get_real_instance ().__class__ == Model2C
323
323
324
+ def test_get_real_instance_with_stale_content_type (self ):
325
+ ctype = ContentType .objects .create (app_label = "tests" , model = "stale" )
326
+ o = Model2A .objects .create (field1 = "A1" , polymorphic_ctype = ctype )
327
+
328
+ assert o .get_real_instance_class () is None
329
+ match = "does not have a corresponding model"
330
+ with pytest .raises (PolymorphicTypeInvalid , match = match ):
331
+ o .get_real_instance ()
332
+
324
333
def test_non_polymorphic (self ):
325
334
self .create_model2abcd ()
326
335
You can’t perform that action at this time.
0 commit comments