You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autodetector.py 62KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. import functools
  2. import re
  3. from itertools import chain
  4. from django.conf import settings
  5. from django.db import models
  6. from django.db.migrations import operations
  7. from django.db.migrations.migration import Migration
  8. from django.db.migrations.operations.models import AlterModelOptions
  9. from django.db.migrations.optimizer import MigrationOptimizer
  10. from django.db.migrations.questioner import MigrationQuestioner
  11. from django.db.migrations.utils import (
  12. COMPILED_REGEX_TYPE, RegexObject, get_migration_name_timestamp,
  13. )
  14. from django.utils.topological_sort import stable_topological_sort
  15. class MigrationAutodetector:
  16. """
  17. Take a pair of ProjectStates and compare them to see what the first would
  18. need doing to make it match the second (the second usually being the
  19. project's current state).
  20. Note that this naturally operates on entire projects at a time,
  21. as it's likely that changes interact (for example, you can't
  22. add a ForeignKey without having a migration to add the table it
  23. depends on first). A user interface may offer single-app usage
  24. if it wishes, with the caveat that it may not always be possible.
  25. """
  26. def __init__(self, from_state, to_state, questioner=None):
  27. self.from_state = from_state
  28. self.to_state = to_state
  29. self.questioner = questioner or MigrationQuestioner()
  30. self.existing_apps = {app for app, model in from_state.models}
  31. def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None):
  32. """
  33. Main entry point to produce a list of applicable changes.
  34. Take a graph to base names on and an optional set of apps
  35. to try and restrict to (restriction is not guaranteed)
  36. """
  37. changes = self._detect_changes(convert_apps, graph)
  38. changes = self.arrange_for_graph(changes, graph, migration_name)
  39. if trim_to_apps:
  40. changes = self._trim_to_apps(changes, trim_to_apps)
  41. return changes
  42. def deep_deconstruct(self, obj):
  43. """
  44. Recursive deconstruction for a field and its arguments.
  45. Used for full comparison for rename/alter; sometimes a single-level
  46. deconstruction will not compare correctly.
  47. """
  48. if isinstance(obj, list):
  49. return [self.deep_deconstruct(value) for value in obj]
  50. elif isinstance(obj, tuple):
  51. return tuple(self.deep_deconstruct(value) for value in obj)
  52. elif isinstance(obj, dict):
  53. return {
  54. key: self.deep_deconstruct(value)
  55. for key, value in obj.items()
  56. }
  57. elif isinstance(obj, functools.partial):
  58. return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords))
  59. elif isinstance(obj, COMPILED_REGEX_TYPE):
  60. return RegexObject(obj)
  61. elif isinstance(obj, type):
  62. # If this is a type that implements 'deconstruct' as an instance method,
  63. # avoid treating this as being deconstructible itself - see #22951
  64. return obj
  65. elif hasattr(obj, 'deconstruct'):
  66. deconstructed = obj.deconstruct()
  67. if isinstance(obj, models.Field):
  68. # we have a field which also returns a name
  69. deconstructed = deconstructed[1:]
  70. path, args, kwargs = deconstructed
  71. return (
  72. path,
  73. [self.deep_deconstruct(value) for value in args],
  74. {
  75. key: self.deep_deconstruct(value)
  76. for key, value in kwargs.items()
  77. },
  78. )
  79. else:
  80. return obj
  81. def only_relation_agnostic_fields(self, fields):
  82. """
  83. Return a definition of the fields that ignores field names and
  84. what related fields actually relate to. Used for detecting renames (as,
  85. of course, the related fields change during renames).
  86. """
  87. fields_def = []
  88. for name, field in sorted(fields):
  89. deconstruction = self.deep_deconstruct(field)
  90. if field.remote_field and field.remote_field.model:
  91. del deconstruction[2]['to']
  92. fields_def.append(deconstruction)
  93. return fields_def
  94. def _detect_changes(self, convert_apps=None, graph=None):
  95. """
  96. Return a dict of migration plans which will achieve the
  97. change from from_state to to_state. The dict has app labels
  98. as keys and a list of migrations as values.
  99. The resulting migrations aren't specially named, but the names
  100. do matter for dependencies inside the set.
  101. convert_apps is the list of apps to convert to use migrations
  102. (i.e. to make initial migrations for, in the usual case)
  103. graph is an optional argument that, if provided, can help improve
  104. dependency generation and avoid potential circular dependencies.
  105. """
  106. # The first phase is generating all the operations for each app
  107. # and gathering them into a big per-app list.
  108. # Then go through that list, order it, and split into migrations to
  109. # resolve dependencies caused by M2Ms and FKs.
  110. self.generated_operations = {}
  111. self.altered_indexes = {}
  112. self.altered_constraints = {}
  113. # Prepare some old/new state and model lists, separating
  114. # proxy models and ignoring unmigrated apps.
  115. self.old_apps = self.from_state.concrete_apps
  116. self.new_apps = self.to_state.apps
  117. self.old_model_keys = set()
  118. self.old_proxy_keys = set()
  119. self.old_unmanaged_keys = set()
  120. self.new_model_keys = set()
  121. self.new_proxy_keys = set()
  122. self.new_unmanaged_keys = set()
  123. for al, mn in self.from_state.models:
  124. model = self.old_apps.get_model(al, mn)
  125. if not model._meta.managed:
  126. self.old_unmanaged_keys.add((al, mn))
  127. elif al not in self.from_state.real_apps:
  128. if model._meta.proxy:
  129. self.old_proxy_keys.add((al, mn))
  130. else:
  131. self.old_model_keys.add((al, mn))
  132. for al, mn in self.to_state.models:
  133. model = self.new_apps.get_model(al, mn)
  134. if not model._meta.managed:
  135. self.new_unmanaged_keys.add((al, mn))
  136. elif (
  137. al not in self.from_state.real_apps or
  138. (convert_apps and al in convert_apps)
  139. ):
  140. if model._meta.proxy:
  141. self.new_proxy_keys.add((al, mn))
  142. else:
  143. self.new_model_keys.add((al, mn))
  144. # Renames have to come first
  145. self.generate_renamed_models()
  146. # Prepare lists of fields and generate through model map
  147. self._prepare_field_lists()
  148. self._generate_through_model_map()
  149. # Generate non-rename model operations
  150. self.generate_deleted_models()
  151. self.generate_created_models()
  152. self.generate_deleted_proxies()
  153. self.generate_created_proxies()
  154. self.generate_altered_options()
  155. self.generate_altered_managers()
  156. # Create the altered indexes and store them in self.altered_indexes.
  157. # This avoids the same computation in generate_removed_indexes()
  158. # and generate_added_indexes().
  159. self.create_altered_indexes()
  160. self.create_altered_constraints()
  161. # Generate index removal operations before field is removed
  162. self.generate_removed_constraints()
  163. self.generate_removed_indexes()
  164. # Generate field operations
  165. self.generate_renamed_fields()
  166. self.generate_removed_fields()
  167. self.generate_added_fields()
  168. self.generate_altered_fields()
  169. self.generate_altered_unique_together()
  170. self.generate_altered_index_together()
  171. self.generate_added_indexes()
  172. self.generate_added_constraints()
  173. self.generate_altered_db_table()
  174. self.generate_altered_order_with_respect_to()
  175. self._sort_migrations()
  176. self._build_migration_list(graph)
  177. self._optimize_migrations()
  178. return self.migrations
  179. def _prepare_field_lists(self):
  180. """
  181. Prepare field lists and a list of the fields that used through models
  182. in the old state so dependencies can be made from the through model
  183. deletion to the field that uses it.
  184. """
  185. self.kept_model_keys = self.old_model_keys & self.new_model_keys
  186. self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys
  187. self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys
  188. self.through_users = {}
  189. self.old_field_keys = {
  190. (app_label, model_name, x)
  191. for app_label, model_name in self.kept_model_keys
  192. for x, y in self.from_state.models[
  193. app_label,
  194. self.renamed_models.get((app_label, model_name), model_name)
  195. ].fields
  196. }
  197. self.new_field_keys = {
  198. (app_label, model_name, x)
  199. for app_label, model_name in self.kept_model_keys
  200. for x, y in self.to_state.models[app_label, model_name].fields
  201. }
  202. def _generate_through_model_map(self):
  203. """Through model map generation."""
  204. for app_label, model_name in sorted(self.old_model_keys):
  205. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  206. old_model_state = self.from_state.models[app_label, old_model_name]
  207. for field_name, field in old_model_state.fields:
  208. old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field(field_name)
  209. if (hasattr(old_field, "remote_field") and getattr(old_field.remote_field, "through", None) and
  210. not old_field.remote_field.through._meta.auto_created):
  211. through_key = (
  212. old_field.remote_field.through._meta.app_label,
  213. old_field.remote_field.through._meta.model_name,
  214. )
  215. self.through_users[through_key] = (app_label, old_model_name, field_name)
  216. @staticmethod
  217. def _resolve_dependency(dependency):
  218. """
  219. Return the resolved dependency and a boolean denoting whether or not
  220. it was swappable.
  221. """
  222. if dependency[0] != '__setting__':
  223. return dependency, False
  224. resolved_app_label, resolved_object_name = getattr(settings, dependency[1]).split('.')
  225. return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True
  226. def _build_migration_list(self, graph=None):
  227. """
  228. Chop the lists of operations up into migrations with dependencies on
  229. each other. Do this by going through an app's list of operations until
  230. one is found that has an outgoing dependency that isn't in another
  231. app's migration yet (hasn't been chopped off its list). Then chop off
  232. the operations before it into a migration and move onto the next app.
  233. If the loops completes without doing anything, there's a circular
  234. dependency (which _should_ be impossible as the operations are
  235. all split at this point so they can't depend and be depended on).
  236. """
  237. self.migrations = {}
  238. num_ops = sum(len(x) for x in self.generated_operations.values())
  239. chop_mode = False
  240. while num_ops:
  241. # On every iteration, we step through all the apps and see if there
  242. # is a completed set of operations.
  243. # If we find that a subset of the operations are complete we can
  244. # try to chop it off from the rest and continue, but we only
  245. # do this if we've already been through the list once before
  246. # without any chopping and nothing has changed.
  247. for app_label in sorted(self.generated_operations):
  248. chopped = []
  249. dependencies = set()
  250. for operation in list(self.generated_operations[app_label]):
  251. deps_satisfied = True
  252. operation_dependencies = set()
  253. for dep in operation._auto_deps:
  254. # Temporarily resolve the swappable dependency to
  255. # prevent circular references. While keeping the
  256. # dependency checks on the resolved model, add the
  257. # swappable dependencies.
  258. original_dep = dep
  259. dep, is_swappable_dep = self._resolve_dependency(dep)
  260. if dep[0] != app_label:
  261. # External app dependency. See if it's not yet
  262. # satisfied.
  263. for other_operation in self.generated_operations.get(dep[0], []):
  264. if self.check_dependency(other_operation, dep):
  265. deps_satisfied = False
  266. break
  267. if not deps_satisfied:
  268. break
  269. else:
  270. if is_swappable_dep:
  271. operation_dependencies.add((original_dep[0], original_dep[1]))
  272. elif dep[0] in self.migrations:
  273. operation_dependencies.add((dep[0], self.migrations[dep[0]][-1].name))
  274. else:
  275. # If we can't find the other app, we add a first/last dependency,
  276. # but only if we've already been through once and checked everything
  277. if chop_mode:
  278. # If the app already exists, we add a dependency on the last migration,
  279. # as we don't know which migration contains the target field.
  280. # If it's not yet migrated or has no migrations, we use __first__
  281. if graph and graph.leaf_nodes(dep[0]):
  282. operation_dependencies.add(graph.leaf_nodes(dep[0])[0])
  283. else:
  284. operation_dependencies.add((dep[0], "__first__"))
  285. else:
  286. deps_satisfied = False
  287. if deps_satisfied:
  288. chopped.append(operation)
  289. dependencies.update(operation_dependencies)
  290. del self.generated_operations[app_label][0]
  291. else:
  292. break
  293. # Make a migration! Well, only if there's stuff to put in it
  294. if dependencies or chopped:
  295. if not self.generated_operations[app_label] or chop_mode:
  296. subclass = type("Migration", (Migration,), {"operations": [], "dependencies": []})
  297. instance = subclass("auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label)
  298. instance.dependencies = list(dependencies)
  299. instance.operations = chopped
  300. instance.initial = app_label not in self.existing_apps
  301. self.migrations.setdefault(app_label, []).append(instance)
  302. chop_mode = False
  303. else:
  304. self.generated_operations[app_label] = chopped + self.generated_operations[app_label]
  305. new_num_ops = sum(len(x) for x in self.generated_operations.values())
  306. if new_num_ops == num_ops:
  307. if not chop_mode:
  308. chop_mode = True
  309. else:
  310. raise ValueError("Cannot resolve operation dependencies: %r" % self.generated_operations)
  311. num_ops = new_num_ops
  312. def _sort_migrations(self):
  313. """
  314. Reorder to make things possible. Reordering may be needed so FKs work
  315. nicely inside the same app.
  316. """
  317. for app_label, ops in sorted(self.generated_operations.items()):
  318. # construct a dependency graph for intra-app dependencies
  319. dependency_graph = {op: set() for op in ops}
  320. for op in ops:
  321. for dep in op._auto_deps:
  322. # Resolve intra-app dependencies to handle circular
  323. # references involving a swappable model.
  324. dep = self._resolve_dependency(dep)[0]
  325. if dep[0] == app_label:
  326. for op2 in ops:
  327. if self.check_dependency(op2, dep):
  328. dependency_graph[op].add(op2)
  329. # we use a stable sort for deterministic tests & general behavior
  330. self.generated_operations[app_label] = stable_topological_sort(ops, dependency_graph)
  331. def _optimize_migrations(self):
  332. # Add in internal dependencies among the migrations
  333. for app_label, migrations in self.migrations.items():
  334. for m1, m2 in zip(migrations, migrations[1:]):
  335. m2.dependencies.append((app_label, m1.name))
  336. # De-dupe dependencies
  337. for migrations in self.migrations.values():
  338. for migration in migrations:
  339. migration.dependencies = list(set(migration.dependencies))
  340. # Optimize migrations
  341. for app_label, migrations in self.migrations.items():
  342. for migration in migrations:
  343. migration.operations = MigrationOptimizer().optimize(migration.operations, app_label=app_label)
  344. def check_dependency(self, operation, dependency):
  345. """
  346. Return True if the given operation depends on the given dependency,
  347. False otherwise.
  348. """
  349. # Created model
  350. if dependency[2] is None and dependency[3] is True:
  351. return (
  352. isinstance(operation, operations.CreateModel) and
  353. operation.name_lower == dependency[1].lower()
  354. )
  355. # Created field
  356. elif dependency[2] is not None and dependency[3] is True:
  357. return (
  358. (
  359. isinstance(operation, operations.CreateModel) and
  360. operation.name_lower == dependency[1].lower() and
  361. any(dependency[2] == x for x, y in operation.fields)
  362. ) or
  363. (
  364. isinstance(operation, operations.AddField) and
  365. operation.model_name_lower == dependency[1].lower() and
  366. operation.name_lower == dependency[2].lower()
  367. )
  368. )
  369. # Removed field
  370. elif dependency[2] is not None and dependency[3] is False:
  371. return (
  372. isinstance(operation, operations.RemoveField) and
  373. operation.model_name_lower == dependency[1].lower() and
  374. operation.name_lower == dependency[2].lower()
  375. )
  376. # Removed model
  377. elif dependency[2] is None and dependency[3] is False:
  378. return (
  379. isinstance(operation, operations.DeleteModel) and
  380. operation.name_lower == dependency[1].lower()
  381. )
  382. # Field being altered
  383. elif dependency[2] is not None and dependency[3] == "alter":
  384. return (
  385. isinstance(operation, operations.AlterField) and
  386. operation.model_name_lower == dependency[1].lower() and
  387. operation.name_lower == dependency[2].lower()
  388. )
  389. # order_with_respect_to being unset for a field
  390. elif dependency[2] is not None and dependency[3] == "order_wrt_unset":
  391. return (
  392. isinstance(operation, operations.AlterOrderWithRespectTo) and
  393. operation.name_lower == dependency[1].lower() and
  394. (operation.order_with_respect_to or "").lower() != dependency[2].lower()
  395. )
  396. # Field is removed and part of an index/unique_together
  397. elif dependency[2] is not None and dependency[3] == "foo_together_change":
  398. return (
  399. isinstance(operation, (operations.AlterUniqueTogether,
  400. operations.AlterIndexTogether)) and
  401. operation.name_lower == dependency[1].lower()
  402. )
  403. # Unknown dependency. Raise an error.
  404. else:
  405. raise ValueError("Can't handle dependency %r" % (dependency,))
  406. def add_operation(self, app_label, operation, dependencies=None, beginning=False):
  407. # Dependencies are (app_label, model_name, field_name, create/delete as True/False)
  408. operation._auto_deps = dependencies or []
  409. if beginning:
  410. self.generated_operations.setdefault(app_label, []).insert(0, operation)
  411. else:
  412. self.generated_operations.setdefault(app_label, []).append(operation)
  413. def swappable_first_key(self, item):
  414. """
  415. Place potential swappable models first in lists of created models (only
  416. real way to solve #22783).
  417. """
  418. try:
  419. model = self.new_apps.get_model(item[0], item[1])
  420. base_names = [base.__name__ for base in model.__bases__]
  421. string_version = "%s.%s" % (item[0], item[1])
  422. if (
  423. model._meta.swappable or
  424. "AbstractUser" in base_names or
  425. "AbstractBaseUser" in base_names or
  426. settings.AUTH_USER_MODEL.lower() == string_version.lower()
  427. ):
  428. return ("___" + item[0], "___" + item[1])
  429. except LookupError:
  430. pass
  431. return item
  432. def generate_renamed_models(self):
  433. """
  434. Find any renamed models, generate the operations for them, and remove
  435. the old entry from the model lists. Must be run before other
  436. model-level generation.
  437. """
  438. self.renamed_models = {}
  439. self.renamed_models_rel = {}
  440. added_models = self.new_model_keys - self.old_model_keys
  441. for app_label, model_name in sorted(added_models):
  442. model_state = self.to_state.models[app_label, model_name]
  443. model_fields_def = self.only_relation_agnostic_fields(model_state.fields)
  444. removed_models = self.old_model_keys - self.new_model_keys
  445. for rem_app_label, rem_model_name in removed_models:
  446. if rem_app_label == app_label:
  447. rem_model_state = self.from_state.models[rem_app_label, rem_model_name]
  448. rem_model_fields_def = self.only_relation_agnostic_fields(rem_model_state.fields)
  449. if model_fields_def == rem_model_fields_def:
  450. if self.questioner.ask_rename_model(rem_model_state, model_state):
  451. model_opts = self.new_apps.get_model(app_label, model_name)._meta
  452. dependencies = []
  453. for field in model_opts.get_fields():
  454. if field.is_relation:
  455. dependencies.extend(self._get_dependencies_for_foreign_key(field))
  456. self.add_operation(
  457. app_label,
  458. operations.RenameModel(
  459. old_name=rem_model_state.name,
  460. new_name=model_state.name,
  461. ),
  462. dependencies=dependencies,
  463. )
  464. self.renamed_models[app_label, model_name] = rem_model_name
  465. renamed_models_rel_key = '%s.%s' % (rem_model_state.app_label, rem_model_state.name)
  466. self.renamed_models_rel[renamed_models_rel_key] = '%s.%s' % (
  467. model_state.app_label,
  468. model_state.name,
  469. )
  470. self.old_model_keys.remove((rem_app_label, rem_model_name))
  471. self.old_model_keys.add((app_label, model_name))
  472. break
  473. def generate_created_models(self):
  474. """
  475. Find all new models (both managed and unmanaged) and make create
  476. operations for them as well as separate operations to create any
  477. foreign key or M2M relationships (these are optimized later, if
  478. possible).
  479. Defer any model options that refer to collections of fields that might
  480. be deferred (e.g. unique_together, index_together).
  481. """
  482. old_keys = self.old_model_keys | self.old_unmanaged_keys
  483. added_models = self.new_model_keys - old_keys
  484. added_unmanaged_models = self.new_unmanaged_keys - old_keys
  485. all_added_models = chain(
  486. sorted(added_models, key=self.swappable_first_key, reverse=True),
  487. sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True)
  488. )
  489. for app_label, model_name in all_added_models:
  490. model_state = self.to_state.models[app_label, model_name]
  491. model_opts = self.new_apps.get_model(app_label, model_name)._meta
  492. # Gather related fields
  493. related_fields = {}
  494. primary_key_rel = None
  495. for field in model_opts.local_fields:
  496. if field.remote_field:
  497. if field.remote_field.model:
  498. if field.primary_key:
  499. primary_key_rel = field.remote_field.model
  500. elif not field.remote_field.parent_link:
  501. related_fields[field.name] = field
  502. # through will be none on M2Ms on swapped-out models;
  503. # we can treat lack of through as auto_created=True, though.
  504. if (getattr(field.remote_field, "through", None) and
  505. not field.remote_field.through._meta.auto_created):
  506. related_fields[field.name] = field
  507. for field in model_opts.local_many_to_many:
  508. if field.remote_field.model:
  509. related_fields[field.name] = field
  510. if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
  511. related_fields[field.name] = field
  512. # Are there indexes/unique|index_together to defer?
  513. indexes = model_state.options.pop('indexes')
  514. constraints = model_state.options.pop('constraints')
  515. unique_together = model_state.options.pop('unique_together', None)
  516. index_together = model_state.options.pop('index_together', None)
  517. order_with_respect_to = model_state.options.pop('order_with_respect_to', None)
  518. # Depend on the deletion of any possible proxy version of us
  519. dependencies = [
  520. (app_label, model_name, None, False),
  521. ]
  522. # Depend on all bases
  523. for base in model_state.bases:
  524. if isinstance(base, str) and "." in base:
  525. base_app_label, base_name = base.split(".", 1)
  526. dependencies.append((base_app_label, base_name, None, True))
  527. # Depend on the other end of the primary key if it's a relation
  528. if primary_key_rel:
  529. dependencies.append((
  530. primary_key_rel._meta.app_label,
  531. primary_key_rel._meta.object_name,
  532. None,
  533. True
  534. ))
  535. # Generate creation operation
  536. self.add_operation(
  537. app_label,
  538. operations.CreateModel(
  539. name=model_state.name,
  540. fields=[d for d in model_state.fields if d[0] not in related_fields],
  541. options=model_state.options,
  542. bases=model_state.bases,
  543. managers=model_state.managers,
  544. ),
  545. dependencies=dependencies,
  546. beginning=True,
  547. )
  548. # Don't add operations which modify the database for unmanaged models
  549. if not model_opts.managed:
  550. continue
  551. # Generate operations for each related field
  552. for name, field in sorted(related_fields.items()):
  553. dependencies = self._get_dependencies_for_foreign_key(field)
  554. # Depend on our own model being created
  555. dependencies.append((app_label, model_name, None, True))
  556. # Make operation
  557. self.add_operation(
  558. app_label,
  559. operations.AddField(
  560. model_name=model_name,
  561. name=name,
  562. field=field,
  563. ),
  564. dependencies=list(set(dependencies)),
  565. )
  566. # Generate other opns
  567. related_dependencies = [
  568. (app_label, model_name, name, True)
  569. for name in sorted(related_fields)
  570. ]
  571. related_dependencies.append((app_label, model_name, None, True))
  572. for index in indexes:
  573. self.add_operation(
  574. app_label,
  575. operations.AddIndex(
  576. model_name=model_name,
  577. index=index,
  578. ),
  579. dependencies=related_dependencies,
  580. )
  581. for constraint in constraints:
  582. self.add_operation(
  583. app_label,
  584. operations.AddConstraint(
  585. model_name=model_name,
  586. constraint=constraint,
  587. ),
  588. dependencies=related_dependencies,
  589. )
  590. if unique_together:
  591. self.add_operation(
  592. app_label,
  593. operations.AlterUniqueTogether(
  594. name=model_name,
  595. unique_together=unique_together,
  596. ),
  597. dependencies=related_dependencies
  598. )
  599. if index_together:
  600. self.add_operation(
  601. app_label,
  602. operations.AlterIndexTogether(
  603. name=model_name,
  604. index_together=index_together,
  605. ),
  606. dependencies=related_dependencies
  607. )
  608. if order_with_respect_to:
  609. self.add_operation(
  610. app_label,
  611. operations.AlterOrderWithRespectTo(
  612. name=model_name,
  613. order_with_respect_to=order_with_respect_to,
  614. ),
  615. dependencies=[
  616. (app_label, model_name, order_with_respect_to, True),
  617. (app_label, model_name, None, True),
  618. ]
  619. )
  620. # Fix relationships if the model changed from a proxy model to a
  621. # concrete model.
  622. if (app_label, model_name) in self.old_proxy_keys:
  623. for related_object in model_opts.related_objects:
  624. self.add_operation(
  625. related_object.related_model._meta.app_label,
  626. operations.AlterField(
  627. model_name=related_object.related_model._meta.object_name,
  628. name=related_object.field.name,
  629. field=related_object.field,
  630. ),
  631. dependencies=[(app_label, model_name, None, True)],
  632. )
  633. def generate_created_proxies(self):
  634. """
  635. Make CreateModel statements for proxy models. Use the same statements
  636. as that way there's less code duplication, but of course for proxy
  637. models it's safe to skip all the pointless field stuff and just chuck
  638. out an operation.
  639. """
  640. added = self.new_proxy_keys - self.old_proxy_keys
  641. for app_label, model_name in sorted(added):
  642. model_state = self.to_state.models[app_label, model_name]
  643. assert model_state.options.get("proxy")
  644. # Depend on the deletion of any possible non-proxy version of us
  645. dependencies = [
  646. (app_label, model_name, None, False),
  647. ]
  648. # Depend on all bases
  649. for base in model_state.bases:
  650. if isinstance(base, str) and "." in base:
  651. base_app_label, base_name = base.split(".", 1)
  652. dependencies.append((base_app_label, base_name, None, True))
  653. # Generate creation operation
  654. self.add_operation(
  655. app_label,
  656. operations.CreateModel(
  657. name=model_state.name,
  658. fields=[],
  659. options=model_state.options,
  660. bases=model_state.bases,
  661. managers=model_state.managers,
  662. ),
  663. # Depend on the deletion of any possible non-proxy version of us
  664. dependencies=dependencies,
  665. )
  666. def generate_deleted_models(self):
  667. """
  668. Find all deleted models (managed and unmanaged) and make delete
  669. operations for them as well as separate operations to delete any
  670. foreign key or M2M relationships (these are optimized later, if
  671. possible).
  672. Also bring forward removal of any model options that refer to
  673. collections of fields - the inverse of generate_created_models().
  674. """
  675. new_keys = self.new_model_keys | self.new_unmanaged_keys
  676. deleted_models = self.old_model_keys - new_keys
  677. deleted_unmanaged_models = self.old_unmanaged_keys - new_keys
  678. all_deleted_models = chain(sorted(deleted_models), sorted(deleted_unmanaged_models))
  679. for app_label, model_name in all_deleted_models:
  680. model_state = self.from_state.models[app_label, model_name]
  681. model = self.old_apps.get_model(app_label, model_name)
  682. # Gather related fields
  683. related_fields = {}
  684. for field in model._meta.local_fields:
  685. if field.remote_field:
  686. if field.remote_field.model:
  687. related_fields[field.name] = field
  688. # through will be none on M2Ms on swapped-out models;
  689. # we can treat lack of through as auto_created=True, though.
  690. if (getattr(field.remote_field, "through", None) and
  691. not field.remote_field.through._meta.auto_created):
  692. related_fields[field.name] = field
  693. for field in model._meta.local_many_to_many:
  694. if field.remote_field.model:
  695. related_fields[field.name] = field
  696. if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
  697. related_fields[field.name] = field
  698. # Generate option removal first
  699. unique_together = model_state.options.pop('unique_together', None)
  700. index_together = model_state.options.pop('index_together', None)
  701. if unique_together:
  702. self.add_operation(
  703. app_label,
  704. operations.AlterUniqueTogether(
  705. name=model_name,
  706. unique_together=None,
  707. )
  708. )
  709. if index_together:
  710. self.add_operation(
  711. app_label,
  712. operations.AlterIndexTogether(
  713. name=model_name,
  714. index_together=None,
  715. )
  716. )
  717. # Then remove each related field
  718. for name in sorted(related_fields):
  719. self.add_operation(
  720. app_label,
  721. operations.RemoveField(
  722. model_name=model_name,
  723. name=name,
  724. )
  725. )
  726. # Finally, remove the model.
  727. # This depends on both the removal/alteration of all incoming fields
  728. # and the removal of all its own related fields, and if it's
  729. # a through model the field that references it.
  730. dependencies = []
  731. for related_object in model._meta.related_objects:
  732. related_object_app_label = related_object.related_model._meta.app_label
  733. object_name = related_object.related_model._meta.object_name
  734. field_name = related_object.field.name
  735. dependencies.append((related_object_app_label, object_name, field_name, False))
  736. if not related_object.many_to_many:
  737. dependencies.append((related_object_app_label, object_name, field_name, "alter"))
  738. for name in sorted(related_fields):
  739. dependencies.append((app_label, model_name, name, False))
  740. # We're referenced in another field's through=
  741. through_user = self.through_users.get((app_label, model_state.name_lower))
  742. if through_user:
  743. dependencies.append((through_user[0], through_user[1], through_user[2], False))
  744. # Finally, make the operation, deduping any dependencies
  745. self.add_operation(
  746. app_label,
  747. operations.DeleteModel(
  748. name=model_state.name,
  749. ),
  750. dependencies=list(set(dependencies)),
  751. )
  752. def generate_deleted_proxies(self):
  753. """Make DeleteModel options for proxy models."""
  754. deleted = self.old_proxy_keys - self.new_proxy_keys
  755. for app_label, model_name in sorted(deleted):
  756. model_state = self.from_state.models[app_label, model_name]
  757. assert model_state.options.get("proxy")
  758. self.add_operation(
  759. app_label,
  760. operations.DeleteModel(
  761. name=model_state.name,
  762. ),
  763. )
  764. def generate_renamed_fields(self):
  765. """Work out renamed fields."""
  766. self.renamed_fields = {}
  767. for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
  768. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  769. old_model_state = self.from_state.models[app_label, old_model_name]
  770. field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  771. # Scan to see if this is actually a rename!
  772. field_dec = self.deep_deconstruct(field)
  773. for rem_app_label, rem_model_name, rem_field_name in sorted(self.old_field_keys - self.new_field_keys):
  774. if rem_app_label == app_label and rem_model_name == model_name:
  775. old_field = old_model_state.get_field_by_name(rem_field_name)
  776. old_field_dec = self.deep_deconstruct(old_field)
  777. if field.remote_field and field.remote_field.model and 'to' in old_field_dec[2]:
  778. old_rel_to = old_field_dec[2]['to']
  779. if old_rel_to in self.renamed_models_rel:
  780. old_field_dec[2]['to'] = self.renamed_models_rel[old_rel_to]
  781. old_field.set_attributes_from_name(rem_field_name)
  782. old_db_column = old_field.get_attname_column()[1]
  783. if (old_field_dec == field_dec or (
  784. # Was the field renamed and db_column equal to the
  785. # old field's column added?
  786. old_field_dec[0:2] == field_dec[0:2] and
  787. dict(old_field_dec[2], db_column=old_db_column) == field_dec[2])):
  788. if self.questioner.ask_rename(model_name, rem_field_name, field_name, field):
  789. self.add_operation(
  790. app_label,
  791. operations.RenameField(
  792. model_name=model_name,
  793. old_name=rem_field_name,
  794. new_name=field_name,
  795. )
  796. )
  797. self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name))
  798. self.old_field_keys.add((app_label, model_name, field_name))
  799. self.renamed_fields[app_label, model_name, field_name] = rem_field_name
  800. break
  801. def generate_added_fields(self):
  802. """Make AddField operations."""
  803. for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
  804. self._generate_added_field(app_label, model_name, field_name)
  805. def _generate_added_field(self, app_label, model_name, field_name):
  806. field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  807. # Fields that are foreignkeys/m2ms depend on stuff
  808. dependencies = []
  809. if field.remote_field and field.remote_field.model:
  810. dependencies.extend(self._get_dependencies_for_foreign_key(field))
  811. # You can't just add NOT NULL fields with no default or fields
  812. # which don't allow empty strings as default.
  813. time_fields = (models.DateField, models.DateTimeField, models.TimeField)
  814. preserve_default = (
  815. field.null or field.has_default() or field.many_to_many or
  816. (field.blank and field.empty_strings_allowed) or
  817. (isinstance(field, time_fields) and field.auto_now)
  818. )
  819. if not preserve_default:
  820. field = field.clone()
  821. if isinstance(field, time_fields) and field.auto_now_add:
  822. field.default = self.questioner.ask_auto_now_add_addition(field_name, model_name)
  823. else:
  824. field.default = self.questioner.ask_not_null_addition(field_name, model_name)
  825. self.add_operation(
  826. app_label,
  827. operations.AddField(
  828. model_name=model_name,
  829. name=field_name,
  830. field=field,
  831. preserve_default=preserve_default,
  832. ),
  833. dependencies=dependencies,
  834. )
  835. def generate_removed_fields(self):
  836. """Make RemoveField operations."""
  837. for app_label, model_name, field_name in sorted(self.old_field_keys - self.new_field_keys):
  838. self._generate_removed_field(app_label, model_name, field_name)
  839. def _generate_removed_field(self, app_label, model_name, field_name):
  840. self.add_operation(
  841. app_label,
  842. operations.RemoveField(
  843. model_name=model_name,
  844. name=field_name,
  845. ),
  846. # We might need to depend on the removal of an
  847. # order_with_respect_to or index/unique_together operation;
  848. # this is safely ignored if there isn't one
  849. dependencies=[
  850. (app_label, model_name, field_name, "order_wrt_unset"),
  851. (app_label, model_name, field_name, "foo_together_change"),
  852. ],
  853. )
  854. def generate_altered_fields(self):
  855. """
  856. Make AlterField operations, or possibly RemovedField/AddField if alter
  857. isn's possible.
  858. """
  859. for app_label, model_name, field_name in sorted(self.old_field_keys & self.new_field_keys):
  860. # Did the field change?
  861. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  862. old_field_name = self.renamed_fields.get((app_label, model_name, field_name), field_name)
  863. old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field(old_field_name)
  864. new_field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  865. # Implement any model renames on relations; these are handled by RenameModel
  866. # so we need to exclude them from the comparison
  867. if hasattr(new_field, "remote_field") and getattr(new_field.remote_field, "model", None):
  868. rename_key = (
  869. new_field.remote_field.model._meta.app_label,
  870. new_field.remote_field.model._meta.model_name,
  871. )
  872. if rename_key in self.renamed_models:
  873. new_field.remote_field.model = old_field.remote_field.model
  874. # Handle ForeignKey which can only have a single to_field.
  875. remote_field_name = getattr(new_field.remote_field, 'field_name', None)
  876. if remote_field_name:
  877. to_field_rename_key = rename_key + (remote_field_name,)
  878. if to_field_rename_key in self.renamed_fields:
  879. new_field.remote_field.field_name = old_field.remote_field.field_name
  880. # Handle ForeignObjects which can have multiple from_fields/to_fields.
  881. from_fields = getattr(new_field, 'from_fields', None)
  882. if from_fields:
  883. from_rename_key = (app_label, model_name)
  884. new_field.from_fields = tuple([
  885. self.renamed_fields.get(from_rename_key + (from_field,), from_field)
  886. for from_field in from_fields
  887. ])
  888. new_field.to_fields = tuple([
  889. self.renamed_fields.get(rename_key + (to_field,), to_field)
  890. for to_field in new_field.to_fields
  891. ])
  892. if hasattr(new_field, "remote_field") and getattr(new_field.remote_field, "through", None):
  893. rename_key = (
  894. new_field.remote_field.through._meta.app_label,
  895. new_field.remote_field.through._meta.model_name,
  896. )
  897. if rename_key in self.renamed_models:
  898. new_field.remote_field.through = old_field.remote_field.through
  899. old_field_dec = self.deep_deconstruct(old_field)
  900. new_field_dec = self.deep_deconstruct(new_field)
  901. if old_field_dec != new_field_dec:
  902. both_m2m = old_field.many_to_many and new_field.many_to_many
  903. neither_m2m = not old_field.many_to_many and not new_field.many_to_many
  904. if both_m2m or neither_m2m:
  905. # Either both fields are m2m or neither is
  906. preserve_default = True
  907. if (old_field.null and not new_field.null and not new_field.has_default() and
  908. not new_field.many_to_many):
  909. field = new_field.clone()
  910. new_default = self.questioner.ask_not_null_alteration(field_name, model_name)
  911. if new_default is not models.NOT_PROVIDED:
  912. field.default = new_default
  913. preserve_default = False
  914. else:
  915. field = new_field
  916. self.add_operation(
  917. app_label,
  918. operations.AlterField(
  919. model_name=model_name,
  920. name=field_name,
  921. field=field,
  922. preserve_default=preserve_default,
  923. )
  924. )
  925. else:
  926. # We cannot alter between m2m and concrete fields
  927. self._generate_removed_field(app_label, model_name, field_name)
  928. self._generate_added_field(app_label, model_name, field_name)
  929. def create_altered_indexes(self):
  930. option_name = operations.AddIndex.option_name
  931. for app_label, model_name in sorted(self.kept_model_keys):
  932. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  933. old_model_state = self.from_state.models[app_label, old_model_name]
  934. new_model_state = self.to_state.models[app_label, model_name]
  935. old_indexes = old_model_state.options[option_name]
  936. new_indexes = new_model_state.options[option_name]
  937. add_idx = [idx for idx in new_indexes if idx not in old_indexes]
  938. rem_idx = [idx for idx in old_indexes if idx not in new_indexes]
  939. self.altered_indexes.update({
  940. (app_label, model_name): {
  941. 'added_indexes': add_idx, 'removed_indexes': rem_idx,
  942. }
  943. })
  944. def generate_added_indexes(self):
  945. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  946. for index in alt_indexes['added_indexes']:
  947. self.add_operation(
  948. app_label,
  949. operations.AddIndex(
  950. model_name=model_name,
  951. index=index,
  952. )
  953. )
  954. def generate_removed_indexes(self):
  955. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  956. for index in alt_indexes['removed_indexes']:
  957. self.add_operation(
  958. app_label,
  959. operations.RemoveIndex(
  960. model_name=model_name,
  961. name=index.name,
  962. )
  963. )
  964. def create_altered_constraints(self):
  965. option_name = operations.AddConstraint.option_name
  966. for app_label, model_name in sorted(self.kept_model_keys):
  967. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  968. old_model_state = self.from_state.models[app_label, old_model_name]
  969. new_model_state = self.to_state.models[app_label, model_name]
  970. old_constraints = old_model_state.options[option_name]
  971. new_constraints = new_model_state.options[option_name]
  972. add_constraints = [c for c in new_constraints if c not in old_constraints]
  973. rem_constraints = [c for c in old_constraints if c not in new_constraints]
  974. self.altered_constraints.update({
  975. (app_label, model_name): {
  976. 'added_constraints': add_constraints, 'removed_constraints': rem_constraints,
  977. }
  978. })
  979. def generate_added_constraints(self):
  980. for (app_label, model_name), alt_constraints in self.altered_constraints.items():
  981. for constraint in alt_constraints['added_constraints']:
  982. self.add_operation(
  983. app_label,
  984. operations.AddConstraint(
  985. model_name=model_name,
  986. constraint=constraint,
  987. )
  988. )
  989. def generate_removed_constraints(self):
  990. for (app_label, model_name), alt_constraints in self.altered_constraints.items():
  991. for constraint in alt_constraints['removed_constraints']:
  992. self.add_operation(
  993. app_label,
  994. operations.RemoveConstraint(
  995. model_name=model_name,
  996. name=constraint.name,
  997. )
  998. )
  999. def _get_dependencies_for_foreign_key(self, field):
  1000. # Account for FKs to swappable models
  1001. swappable_setting = getattr(field, 'swappable_setting', None)
  1002. if swappable_setting is not None:
  1003. dep_app_label = "__setting__"
  1004. dep_object_name = swappable_setting
  1005. else:
  1006. dep_app_label = field.remote_field.model._meta.app_label
  1007. dep_object_name = field.remote_field.model._meta.object_name
  1008. dependencies = [(dep_app_label, dep_object_name, None, True)]
  1009. if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
  1010. dependencies.append((
  1011. field.remote_field.through._meta.app_label,
  1012. field.remote_field.through._meta.object_name,
  1013. None,
  1014. True,
  1015. ))
  1016. return dependencies
  1017. def _generate_altered_foo_together(self, operation):
  1018. option_name = operation.option_name
  1019. for app_label, model_name in sorted(self.kept_model_keys):
  1020. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1021. old_model_state = self.from_state.models[app_label, old_model_name]
  1022. new_model_state = self.to_state.models[app_label, model_name]
  1023. # We run the old version through the field renames to account for those
  1024. old_value = old_model_state.options.get(option_name)
  1025. old_value = {
  1026. tuple(
  1027. self.renamed_fields.get((app_label, model_name, n), n)
  1028. for n in unique
  1029. )
  1030. for unique in old_value
  1031. } if old_value else set()
  1032. new_value = new_model_state.options.get(option_name)
  1033. new_value = set(new_value) if new_value else set()
  1034. if old_value != new_value:
  1035. dependencies = []
  1036. for foo_togethers in new_value:
  1037. for field_name in foo_togethers:
  1038. field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  1039. if field.remote_field and field.remote_field.model:
  1040. dependencies.extend(self._get_dependencies_for_foreign_key(field))
  1041. self.add_operation(
  1042. app_label,
  1043. operation(
  1044. name=model_name,
  1045. **{option_name: new_value}
  1046. ),
  1047. dependencies=dependencies,
  1048. )
  1049. def generate_altered_unique_together(self):
  1050. self._generate_altered_foo_together(operations.AlterUniqueTogether)
  1051. def generate_altered_index_together(self):
  1052. self._generate_altered_foo_together(operations.AlterIndexTogether)
  1053. def generate_altered_db_table(self):
  1054. models_to_check = self.kept_model_keys.union(self.kept_proxy_keys, self.kept_unmanaged_keys)
  1055. for app_label, model_name in sorted(models_to_check):
  1056. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1057. old_model_state = self.from_state.models[app_label, old_model_name]
  1058. new_model_state = self.to_state.models[app_label, model_name]
  1059. old_db_table_name = old_model_state.options.get('db_table')
  1060. new_db_table_name = new_model_state.options.get('db_table')
  1061. if old_db_table_name != new_db_table_name:
  1062. self.add_operation(
  1063. app_label,
  1064. operations.AlterModelTable(
  1065. name=model_name,
  1066. table=new_db_table_name,
  1067. )
  1068. )
  1069. def generate_altered_options(self):
  1070. """
  1071. Work out if any non-schema-affecting options have changed and make an
  1072. operation to represent them in state changes (in case Python code in
  1073. migrations needs them).
  1074. """
  1075. models_to_check = self.kept_model_keys.union(
  1076. self.kept_proxy_keys,
  1077. self.kept_unmanaged_keys,
  1078. # unmanaged converted to managed
  1079. self.old_unmanaged_keys & self.new_model_keys,
  1080. # managed converted to unmanaged
  1081. self.old_model_keys & self.new_unmanaged_keys,
  1082. )
  1083. for app_label, model_name in sorted(models_to_check):
  1084. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1085. old_model_state = self.from_state.models[app_label, old_model_name]
  1086. new_model_state = self.to_state.models[app_label, model_name]
  1087. old_options = {
  1088. key: value for key, value in old_model_state.options.items()
  1089. if key in AlterModelOptions.ALTER_OPTION_KEYS
  1090. }
  1091. new_options = {
  1092. key: value for key, value in new_model_state.options.items()
  1093. if key in AlterModelOptions.ALTER_OPTION_KEYS
  1094. }
  1095. if old_options != new_options:
  1096. self.add_operation(
  1097. app_label,
  1098. operations.AlterModelOptions(
  1099. name=model_name,
  1100. options=new_options,
  1101. )
  1102. )
  1103. def generate_altered_order_with_respect_to(self):
  1104. for app_label, model_name in sorted(self.kept_model_keys):
  1105. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1106. old_model_state = self.from_state.models[app_label, old_model_name]
  1107. new_model_state = self.to_state.models[app_label, model_name]
  1108. if (old_model_state.options.get("order_with_respect_to") !=
  1109. new_model_state.options.get("order_with_respect_to")):
  1110. # Make sure it comes second if we're adding
  1111. # (removal dependency is part of RemoveField)
  1112. dependencies = []
  1113. if new_model_state.options.get("order_with_respect_to"):
  1114. dependencies.append((
  1115. app_label,
  1116. model_name,
  1117. new_model_state.options["order_with_respect_to"],
  1118. True,
  1119. ))
  1120. # Actually generate the operation
  1121. self.add_operation(
  1122. app_label,
  1123. operations.AlterOrderWithRespectTo(
  1124. name=model_name,
  1125. order_with_respect_to=new_model_state.options.get('order_with_respect_to'),
  1126. ),
  1127. dependencies=dependencies,
  1128. )
  1129. def generate_altered_managers(self):
  1130. for app_label, model_name in sorted(self.kept_model_keys):
  1131. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1132. old_model_state = self.from_state.models[app_label, old_model_name]
  1133. new_model_state = self.to_state.models[app_label, model_name]
  1134. if old_model_state.managers != new_model_state.managers:
  1135. self.add_operation(
  1136. app_label,
  1137. operations.AlterModelManagers(
  1138. name=model_name,
  1139. managers=new_model_state.managers,
  1140. )
  1141. )
  1142. def arrange_for_graph(self, changes, graph, migration_name=None):
  1143. """
  1144. Take a result from changes() and a MigrationGraph, and fix the names
  1145. and dependencies of the changes so they extend the graph from the leaf
  1146. nodes for each app.
  1147. """
  1148. leaves = graph.leaf_nodes()
  1149. name_map = {}
  1150. for app_label, migrations in list(changes.items()):
  1151. if not migrations:
  1152. continue
  1153. # Find the app label's current leaf node
  1154. app_leaf = None
  1155. for leaf in leaves:
  1156. if leaf[0] == app_label:
  1157. app_leaf = leaf
  1158. break
  1159. # Do they want an initial migration for this app?
  1160. if app_leaf is None and not self.questioner.ask_initial(app_label):
  1161. # They don't.
  1162. for migration in migrations:
  1163. name_map[(app_label, migration.name)] = (app_label, "__first__")
  1164. del changes[app_label]
  1165. continue
  1166. # Work out the next number in the sequence
  1167. if app_leaf is None:
  1168. next_number = 1
  1169. else:
  1170. next_number = (self.parse_number(app_leaf[1]) or 0) + 1
  1171. # Name each migration
  1172. for i, migration in enumerate(migrations):
  1173. if i == 0 and app_leaf:
  1174. migration.dependencies.append(app_leaf)
  1175. if i == 0 and not app_leaf:
  1176. new_name = "0001_%s" % migration_name if migration_name else "0001_initial"
  1177. else:
  1178. new_name = "%04i_%s" % (
  1179. next_number,
  1180. migration_name or self.suggest_name(migration.operations)[:100],
  1181. )
  1182. name_map[(app_label, migration.name)] = (app_label, new_name)
  1183. next_number += 1
  1184. migration.name = new_name
  1185. # Now fix dependencies
  1186. for migrations in changes.values():
  1187. for migration in migrations:
  1188. migration.dependencies = [name_map.get(d, d) for d in migration.dependencies]
  1189. return changes
  1190. def _trim_to_apps(self, changes, app_labels):
  1191. """
  1192. Take changes from arrange_for_graph() and set of app labels, and return
  1193. a modified set of changes which trims out as many migrations that are
  1194. not in app_labels as possible. Note that some other migrations may
  1195. still be present as they may be required dependencies.
  1196. """
  1197. # Gather other app dependencies in a first pass
  1198. app_dependencies = {}
  1199. for app_label, migrations in changes.items():
  1200. for migration in migrations:
  1201. for dep_app_label, name in migration.dependencies:
  1202. app_dependencies.setdefault(app_label, set()).add(dep_app_label)
  1203. required_apps = set(app_labels)
  1204. # Keep resolving till there's no change
  1205. old_required_apps = None
  1206. while old_required_apps != required_apps:
  1207. old_required_apps = set(required_apps)
  1208. required_apps.update(*[app_dependencies.get(app_label, ()) for app_label in required_apps])
  1209. # Remove all migrations that aren't needed
  1210. for app_label in list(changes):
  1211. if app_label not in required_apps:
  1212. del changes[app_label]
  1213. return changes
  1214. @classmethod
  1215. def suggest_name(cls, ops):
  1216. """
  1217. Given a set of operations, suggest a name for the migration they might
  1218. represent. Names are not guaranteed to be unique, but put some effort
  1219. into the fallback name to avoid VCS conflicts if possible.
  1220. """
  1221. if len(ops) == 1:
  1222. if isinstance(ops[0], operations.CreateModel):
  1223. return ops[0].name_lower
  1224. elif isinstance(ops[0], operations.DeleteModel):
  1225. return "delete_%s" % ops[0].name_lower
  1226. elif isinstance(ops[0], operations.AddField):
  1227. return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
  1228. elif isinstance(ops[0], operations.RemoveField):
  1229. return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
  1230. elif ops:
  1231. if all(isinstance(o, operations.CreateModel) for o in ops):
  1232. return "_".join(sorted(o.name_lower for o in ops))
  1233. return "auto_%s" % get_migration_name_timestamp()
  1234. @classmethod
  1235. def parse_number(cls, name):
  1236. """
  1237. Given a migration name, try to extract a number from the beginning of
  1238. it. If no number is found, return None.
  1239. """
  1240. match = re.match(r'^\d+', name)
  1241. if match:
  1242. return int(match.group())
  1243. return None