1
0
mirror of https://github.com/django/django.git synced 2025-01-03 06:55:47 +00:00

Fixed #34420 -- Corrected the order of imports in generated migration files.

This commit is contained in:
Andy Chosak 2023-03-18 14:02:12 -04:00 committed by Mariusz Felisiak
parent 0eb3e9bd75
commit b295b31171
2 changed files with 11 additions and 2 deletions

View File

@ -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"] += (

View File

@ -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,
)