8000 Fixed #29177: FKs accessible in subsequent migrations for unmanaged models by michalnik · Pull Request #19452 · django/django · GitHub
[go: up one dir, main page]

Skip to content

Fixed #29177: FKs accessible in subsequent migrations for unmanaged models #19452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions django/db/migrations/autodetector.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def _detect_changes(self, convert_apps=None, graph=None):
self.renamed_fields = {}

# Prepare some old/new state and model lists, separating
# proxy models and ignoring unmigrated apps.
# proxy models and unmanaged models(for later usage?).
self.old_model_keys = set()
self.old_proxy_keys = set()
self.old_unmanaged_keys = set()
Expand Down Expand Up @@ -240,14 +240,14 @@ def _prepare_field_lists(self):
self.through_users = {}
self.old_field_keys = {
(app_label, model_name, field_name)
for app_label, model_name in self.kept_model_keys
for app_label, model_name in self.kept_model_keys | self.kept_unmanaged_keys
for field_name in self.from_state.models[
app_label, self.renamed_models.get((app_label, model_name), model_name)
].fields
}
self.new_field_keys = {
(app_label, model_name, field_name)
for app_label, model_name in self.kept_model_keys
for app_label, model_name in self.kept_model_keys | self.kept_unmanaged_keys
for field_name in self.to_state.models[app_label, model_name].fields
}

Expand Down Expand Up @@ -741,10 +741,6 @@ def generate_created_models(self):
beginning=True,
)

# Don't add operations which modify the database for unmanaged models
if not model_state.options.get("managed", True):
continue

# Generate operations for each related field
for name, field in sorted(related_fields.items()):
dependencies = self._get_dependencies_for_foreign_key(
Expand Down
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.db import models


class Foo(models.Model):
class Meta:
managed = True


class Boo(models.Model):
foo = models.ForeignKey("Foo", on_delete=models.CASCADE)

class Meta:
managed = False
91 changes: 90 additions & 1 deletion tests/migrations/test_autodetector.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,14 +716,18 @@ class AutodetectorTests(BaseAutodetectorTests):
"testapp", "AuthorUnmanaged", [], {}, ("testapp.author",)
)
author_unmanaged_default_pk = ModelState(
"testapp", "Author", [("id", models.AutoField(primary_key=True))]
"testapp",
"Author",
[("id", models.AutoField(primary_key=True))],
{"managed": False},
)
author_unmanaged_custom_pk = ModelState(
"testapp",
"Author",
[
("pk_field", models.IntegerField(primary_key=True)),
],
{"managed": False},
)
author_with_m2m = ModelState(
"testapp",
Expand Down Expand Up @@ -1071,6 +1075,34 @@ class AutodetectorTests(BaseAutodetectorTests):
"unique_together": {("title", "newfield2")},
},
)
book_unmanaged_with_fk = ModelState(
"otherapp",
"BookUnmanaged",
[
("author", models.ForeignKey("testapp.Author", models.CASCADE)),
("name", models.CharField(max_length=200)),
("published", models.PositiveSmallIntegerField()),
],
{"managed": False},
)
book_unmanaged_without_fk = ModelState(
"otherapp",
"BookUnmanaged",
[
("name", models.CharField(max_length=200)),
],
{"managed": False},
)
book_unmanaged_rename_fk = ModelState(
"otherapp",
"BookUnmanaged",
[
("author_old", models.ForeignKey("testapp.Author", models.CASCADE)),
("name_old", models.CharField(max_length=200)),
("published", models.PositiveSmallIntegerField()),
],
{"managed": False},
)
attribution = ModelState(
"otherapp",
"Attribution",
Expand Down Expand Up @@ -3711,6 +3743,63 @@ def test_unmanaged_custom_pk(self):
fk_field = changes["otherapp"][0].operations[0].fields[2][1]
self.assertEqual(fk_field.remote_field.model, "testapp.Author")

def test_unmanaged_with_fk(self):
"""
#29177 - The autodetector must correctly deal with FK of unmanaged
on managed models - add FK to unmanaged model
fields(and other fields also)
"""
changes = self.get_changes([], [self.author_empty, self.book_unmanaged_with_fk])
fk_field = changes["otherapp"][0].operations[0].fields[2][1]
name_field = changes["otherapp"][0].operations[0].fields[0]
published_field = changes["otherapp"][0].operations[0].fields[1]
self.assertEqual(fk_field.remote_field.model, "testapp.Author")
self.assertEqual(name_field[0], "name")
self.assertEqual(name_field[1].get_internal_type(), "CharField")
self.assertEqual(published_field[0], "published")
self.assertEqual(
published_field[1].get_internal_type(), "PositiveSmallIntegerField"
)

def test_unmanaged_removing_fk(self):
"""
#29177 - The autodetector must correctly deal with FK of unmanaged
on managed models - remove FK from unmanaged model
fields(and other fields also)
"""
changes = self.get_changes(
[self.author_empty, self.book_unmanaged_with_fk],
[self.author_empty, self.book_unmanaged_without_fk],
)
remove_fk = changes["otherapp"][0].operations[0]
remove_published = changes["otherapp"][0].operations[1]
self.assertEqual(remove_fk.name, "author")
self.assertTrue("REMOVAL" in remove_fk.category.__str__())
self.assertEqual(remove_published.name, "published")
self.assertTrue("REMOVAL" in remove_published.category.__str__())

def test_unmanaged_rename_fk(self):
"""
#29177 - The autodetector must correctly deal with FK of unmanaged
on managed models - rename FK(and other field also)
"""
changes = self.get_changes(
[self.author_empty, self.book_unmanaged_with_fk],
[self.author_empty, self.book_unmanaged_rename_fk],
)
remove_author_fk = changes["otherapp"][0].operations[0]
remove_name = changes["otherapp"][0].operations[1]
add_author_old_fk = changes["otherapp"][0].operations[2]
add_name_old = changes["otherapp"][0].operations[3]
self.assertEqual(remove_author_fk.name, "author")
self.assertTrue("REMOVAL" in remove_author_fk.category.__str__())
self.assertEqual(remove_name.name, "name")
self.assertTrue("REMOVAL" in remove_name.category.__str__())
self.assertEqual(add_author_old_fk.name, "author_old")
self.assertTrue("ADDITION" in add_author_old_fk.category.__str__())
self.assertEqual(add_name_old.name, "name_old")
self.assertTrue("ADDITION" in add_name_old.category.__str__())

@override_settings(AUTH_USER_MODEL="thirdapp.CustomUser")
def test_swappable(self):
with isolate_lru_cache(apps.get_swappable_settings_name):
Expand Down
227 changes: 227 additions & 0 deletions tests/migrations/test_autodetector_unmanaged.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import io
import textwrap
from pathlib import Path

from migrations.test_base import MigrationTestBase

from django.core.exceptions import FieldError
from django.core.management import call_command
from django.test import TransactionTestCase
from django.test.utils import override_settings


class AutodetectorUnmanagedModelTest(MigrationTestBase, TransactionTestCase):
"""Regression test for bug in autodetector with FK to managed=False model."""

# Consider also other cases to test, but the
# 'test_create_model_migrate_crashes_on_missing_fk' is the proove of a bug

@override_settings(
DEFAULT_AUTO_FIELD="django.db.models.AutoField",
INSTALLED_APPS=["migrations.migrations_test_apps.unmanaged_model_with_fk"],
)
def test_create_model_migrate_crashes_on_missing_fk(self):
out = io.StringIO()
with self.temporary_migration_module("unmanaged_model_with_fk") as tmp_dir:
call_command("makemigrations", "unmanaged_model_with_fk", verbosity=0)
call_command("migrate", "unmanaged_model_with_fk", verbosity=0)
with open(Path(tmp_dir) / "0002_custom.py", "w") as custom_migration_file:
custom_migration_content = textwrap.dedent(
"""
from django.db import migrations


def forwards_func(apps, schema_editor):
klass_Boo = apps.get_model("unmanaged_model_with_fk", "Boo")
klass_Boo.objects.filter(foo=1)


class Migration(migrations.Migration):

dependencies = [
('unmanaged_model_with_fk', '0001_initial'),
]

operations = [
migrations.RunPython(
forwards_func,
reverse_code=migrations.RunPython.noop
),
]
"""
)
custom_migration_file.write(custom_migration_content)
try:
call_command("migrate", "unmanaged_model_with_fk", stdout=out)
except FieldError:
# this is the bug from #29177, it can not find FK in managed=False model
pass
self.assertIn("OK", out.getvalue())

@override_settings(
DEFAULT_AUTO_FIELD="django.db.models.AutoField",
INSTALLED_APPS=["migrations.migrations_test_apps.unmanaged_model_with_fk"],
)
def test_add_field_operation_is_detected(self):
out = io.StringIO()
initial_migration_content = textwrap.dedent(
"""
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Foo',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID'
)
),
],
options={
'managed': True,
},
),
migrations.CreateModel(
name='Boo',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID'
)
),
],
options={
'managed': False,
},
),
]
"""
)
with self.temporary_migration_module("unmanaged_model_with_fk") as tmp_dir:
with open(Path(tmp_dir) / "0001_initial.py", "w") as initial_migration_file:
initial_migration_file.write(initial_migration_content)
call_command(
"makemigrations",
"unmanaged_model_with_fk",
dry_run=True,
verbosity=3,
stdout=out,
)
# explanation: currently as a side effect of a bug in #29177,
# there is: "No changes detected in app...", but
# AddField( ... name='foo' ...) should be there
migration_content = out.getvalue()
add_field_content = migration_content[migration_content.find("AddField") :]
add_field_content = add_field_content[: add_field_content.find(")") + 1]
self.assertIn("AddField", add_field_content)
self.assertIn("name='foo'", add_field_content)

@override_settings(
DEFAULT_AUTO_FIELD="django.db.models.AutoField",
INSTALLED_APPS=["migrations.migrations_test_apps.unmanaged_model_with_fk"],
)
def test_remove_field_operation_is_detected(self):
out = io.StringIO()
initial_migration_content = textwrap.dedent(
"""
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Foo',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID'
)
),
],
options={
'managed': True,
},
),
migrations.CreateModel(
name='Boo',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID'
)
),
(
'foo',
models.ForeignKey(
on_delete=models.deletion.CASCADE,
to='unmanaged_model_with_fk.foo',
)
),
(
'fk_foo',
models.ForeignKey(
on_delete=models.deletion.CASCADE,
to='unmanaged_model_with_fk.foo',
)
),
],
options={
'managed': False,
},
),
]
"""
)
with self.temporary_migration_module("unmanaged_model_with_fk") as tmp_dir:
with open(Path(tmp_dir) / "0001_initial.py", "w") as initial_migration_file:
initial_migration_file.write(initial_migration_content)
call_command(
"makemigrations",
"unmanaged_model_with_fk",
dry_run=True,
verbosity=3,
stdout=out,
)
# explanation: currently as a side effect of a bug in #29177,
# there is: "No changes detected in app...", but
# RemoveField( ... name='fk_foo' ...) should be there
migration_content = out.getvalue()
remove_field_content = migration_content[
migration_content.find("RemoveField") :
]
remove_field_content = remove_field_content[
: remove_field_content.find(")") + 1
]
self.assertIn("RemoveField", remove_field_content)
self.assertIn("name='fk_foo'", remove_field_content)
0