Skip to content

Commit

Permalink
Fixed #26827 -- Improved ModelState error message when relations refe…
Browse files Browse the repository at this point in the history
…r model classes.
  • Loading branch information
prashantpandey9 authored and felixxm committed Nov 23, 2023
1 parent a89c715 commit a8adb6a
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,7 @@ answer newbie questions, and generally made Django that much better:
plisk
[email protected]
[email protected]
Prashant Pandey <https://prashantpandey9.in>
Preston Holmes <[email protected]>
Preston Timmons <[email protected]>
Priyank Panchal <[email protected]>
Expand Down
10 changes: 6 additions & 4 deletions django/db/migrations/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,13 +738,15 @@ def __init__(
# Sanity-check that relation fields are NOT referring to a model class.
if field.is_relation and hasattr(field.related_model, "_meta"):
raise ValueError(
'ModelState.fields cannot refer to a model class - "%s.to" does. '
"Use a string reference instead." % name
'Model fields in "ModelState.fields" cannot refer to a model class '
f'- "{self.app_label}.{self.name}.{name}.to" does. Use a string '
"reference instead."
)
if field.many_to_many and hasattr(field.remote_field.through, "_meta"):
raise ValueError(
'ModelState.fields cannot refer to a model class - "%s.through" '
"does. Use a string reference instead." % name
'Model fields in "ModelState.fields" cannot refer to a model class '
f'- "{self.app_label}.{self.name}.{name}.through" does. Use a '
"string reference instead."
)
# Sanity-check that indexes have their name set.
for index in self.options["indexes"]:
Expand Down
8 changes: 4 additions & 4 deletions tests/migrations/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1651,8 +1651,8 @@ def test_sanity_check_to(self):
field = models.ForeignKey(UnicodeModel, models.CASCADE)
with self.assertRaisesMessage(
ValueError,
'ModelState.fields cannot refer to a model class - "field.to" does. '
"Use a string reference instead.",
'Model fields in "ModelState.fields" cannot refer to a model class - '
'"app.Model.field.to" does. Use a string reference instead.',
):
ModelState("app", "Model", [("field", field)])

Expand All @@ -1661,8 +1661,8 @@ def test_sanity_check_through(self):
field.remote_field.through = UnicodeModel
with self.assertRaisesMessage(
ValueError,
'ModelState.fields cannot refer to a model class - "field.through" does. '
"Use a string reference instead.",
'Model fields in "ModelState.fields" cannot refer to a model class - '
'"app.Model.field.through" does. Use a string reference instead.',
):
ModelState("app", "Model", [("field", field)])

Expand Down

0 comments on commit a8adb6a

Please sign in to comment.