MCPcopy
hub / github.com/django/django / MigrationWriter

Class MigrationWriter

django/db/migrations/writer.py:118–302  ·  view source on GitHub ↗

Take a Migration instance and is able to produce the contents of the migration file from it.

Source from the content-addressed store, hash-verified

116
117
118class MigrationWriter:
119 """
120 Take a Migration instance and is able to produce the contents
121 of the migration file from it.
122 """
123
124 def __init__(self, migration, include_header=True):
125 self.migration = migration
126 self.include_header = include_header
127 self.needs_manual_porting = False
128
129 def as_string(self):
130 """Return a string of the file contents."""
131 items = {
132 "replaces_str": "",
133 "initial_str": "",
134 "run_before_str": "",
135 "atomic_str": "",
136 }
137
138 imports = set()
139
140 # Deconstruct operations
141 operations = []
142 for operation in self.migration.operations:
143 operation_string, operation_imports = OperationWriter(operation).serialize()
144 imports.update(operation_imports)
145 operations.append(operation_string)
146 items["operations"] = "\n".join(operations) + "\n" if operations else ""
147
148 # Format dependencies and write out swappable dependencies right
149 dependencies = []
150 for dependency in self.migration.dependencies:
151 if dependency[0] == "__setting__":
152 dependencies.append(
153 " migrations.swappable_dependency(settings.%s),"
154 % dependency[1]
155 )
156 imports.add("from django.conf import settings")
157 else:
158 dependencies.append(" %s," % self.serialize(dependency)[0])
159 items["dependencies"] = (
160 "\n".join(sorted(dependencies)) + "\n" if dependencies else ""
161 )
162
163 # Format imports nicely, swapping imports of functions from migration
164 # files for comments
165 migration_imports = set()
166 for line in list(imports):
167 if re.match(r"^import (.*)\.\d+[^\s]*$", line):
168 migration_imports.add(line.split("import")[1].strip())
169 imports.remove(line)
170 self.needs_manual_porting = True
171
172 # django.db.migrations is always used, but models import may not be.
173 # If models import exists, merge it with migrations import.
174 if "from django.db import models" in imports:
175 imports.discard("from django.db import models")

Callers 15

handleMethod · 0.90
write_migration_filesMethod · 0.90
handle_mergeMethod · 0.90
handleMethod · 0.90
test_simple_migrationMethod · 0.90
test_migration_pathMethod · 0.90
test_custom_operationMethod · 0.90
test_sorted_importsMethod · 0.90

Calls

no outgoing calls