From b295b311712b598c053f7fa8cf6e6882217e35d9 Mon Sep 17 00:00:00 2001 From: Andy Chosak Date: Sat, 18 Mar 2023 14:02:12 -0400 Subject: [PATCH] Fixed #34420 -- Corrected the order of imports in generated migration files. --- django/db/migrations/writer.py | 5 ++++- tests/migrations/test_writer.py | 8 +++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py index a59f0c8dcb..79b89b269d 100644 --- a/django/db/migrations/writer.py +++ b/django/db/migrations/writer.py @@ -175,7 +175,10 @@ class MigrationWriter: # Sort imports by the package / module to be imported (the part after # "from" in "from ... import ..." or after "import" in "import ..."). - sorted_imports = sorted(imports, key=lambda i: i.split()[1]) + # First group the "import" statements, then "from ... import ...". + sorted_imports = sorted( + imports, key=lambda i: (i.split()[0] == "from", i.split()[1]) + ) items["imports"] = "\n".join(sorted_imports) + "\n" if imports else "" if migration_imports: items["imports"] += ( diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py index 1c11c68e97..c6638b3083 100644 --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -7,6 +7,7 @@ import os import pathlib import re import sys +import time import uuid import zoneinfo from types import NoneType @@ -912,13 +913,18 @@ class WriterTests(SimpleTestCase): ), ), ), + migrations.AddField( + "mymodel", + "myfield2", + models.FloatField(default=time.time), + ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn( - "import datetime\nfrom django.db import migrations, models\n", + "import datetime\nimport time\nfrom django.db import migrations, models\n", output, )