diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 8930d6ef4a..6737570074 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -187,7 +187,9 @@ class RelatedField(FieldCacheMixin, Field): return errors def _check_relation_model_exists(self): - rel_is_missing = self.remote_field.model not in self.opts.apps.get_models() + rel_is_missing = self.remote_field.model not in self.opts.apps.get_models( + include_auto_created=True + ) rel_is_string = isinstance(self.remote_field.model, str) model_name = ( self.remote_field.model diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py index e539d4e6fb..9b69ae4151 100644 --- a/tests/invalid_models_tests/test_relative_fields.py +++ b/tests/invalid_models_tests/test_relative_fields.py @@ -89,6 +89,23 @@ class RelativeFieldTests(SimpleTestCase): field = Model._meta.get_field("m2m") self.assertEqual(field.check(from_model=Model), []) + @isolate_apps("invalid_models_tests") + def test_auto_created_through_model(self): + class OtherModel(models.Model): + pass + + class M2MModel(models.Model): + many_to_many_rel = models.ManyToManyField(OtherModel) + + class O2OModel(models.Model): + one_to_one_rel = models.OneToOneField( + "invalid_models_tests.M2MModel_many_to_many_rel", + on_delete=models.CASCADE, + ) + + field = O2OModel._meta.get_field("one_to_one_rel") + self.assertEqual(field.check(from_model=O2OModel), []) + def test_many_to_many_with_useless_options(self): class Model(models.Model): name = models.CharField(max_length=20)