autodetector.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  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. the related fields change during renames).
  86. """
  87. fields_def = []
  88. for name, field in sorted(fields.items()):
  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, field_name)
  191. for app_label, model_name in self.kept_model_keys
  192. for field_name 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, field_name)
  199. for app_label, model_name in self.kept_model_keys
  200. for field_name 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 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)
  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' % (
  466. rem_model_state.app_label,
  467. rem_model_state.name_lower,
  468. )
  469. self.renamed_models_rel[renamed_models_rel_key] = '%s.%s' % (
  470. model_state.app_label,
  471. model_state.name_lower,
  472. )
  473. self.old_model_keys.remove((rem_app_label, rem_model_name))
  474. self.old_model_keys.add((app_label, model_name))
  475. break
  476. def generate_created_models(self):
  477. """
  478. Find all new models (both managed and unmanaged) and make create
  479. operations for them as well as separate operations to create any
  480. foreign key or M2M relationships (these are optimized later, if
  481. possible).
  482. Defer any model options that refer to collections of fields that might
  483. be deferred (e.g. unique_together, index_together).
  484. """
  485. old_keys = self.old_model_keys | self.old_unmanaged_keys
  486. added_models = self.new_model_keys - old_keys
  487. added_unmanaged_models = self.new_unmanaged_keys - old_keys
  488. all_added_models = chain(
  489. sorted(added_models, key=self.swappable_first_key, reverse=True),
  490. sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True)
  491. )
  492. for app_label, model_name in all_added_models:
  493. model_state = self.to_state.models[app_label, model_name]
  494. model_opts = self.new_apps.get_model(app_label, model_name)._meta
  495. # Gather related fields
  496. related_fields = {}
  497. primary_key_rel = None
  498. for field in model_opts.local_fields:
  499. if field.remote_field:
  500. if field.remote_field.model:
  501. if field.primary_key:
  502. primary_key_rel = field.remote_field.model
  503. elif not field.remote_field.parent_link:
  504. related_fields[field.name] = field
  505. # through will be none on M2Ms on swapped-out models;
  506. # we can treat lack of through as auto_created=True, though.
  507. if (getattr(field.remote_field, "through", None) and
  508. not field.remote_field.through._meta.auto_created):
  509. related_fields[field.name] = field
  510. for field in model_opts.local_many_to_many:
  511. if field.remote_field.model:
  512. related_fields[field.name] = field
  513. if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
  514. related_fields[field.name] = field
  515. # Are there indexes/unique|index_together to defer?
  516. indexes = model_state.options.pop('indexes')
  517. constraints = model_state.options.pop('constraints')
  518. unique_together = model_state.options.pop('unique_together', None)
  519. index_together = model_state.options.pop('index_together', None)
  520. order_with_respect_to = model_state.options.pop('order_with_respect_to', None)
  521. # Depend on the deletion of any possible proxy version of us
  522. dependencies = [
  523. (app_label, model_name, None, False),
  524. ]
  525. # Depend on all bases
  526. for base in model_state.bases:
  527. if isinstance(base, str) and "." in base:
  528. base_app_label, base_name = base.split(".", 1)
  529. dependencies.append((base_app_label, base_name, None, True))
  530. # Depend on the removal of base fields if the new model has
  531. # a field with the same name.
  532. old_base_model_state = self.from_state.models.get((base_app_label, base_name))
  533. new_base_model_state = self.to_state.models.get((base_app_label, base_name))
  534. if old_base_model_state and new_base_model_state:
  535. removed_base_fields = set(old_base_model_state.fields).difference(
  536. new_base_model_state.fields,
  537. ).intersection(model_state.fields)
  538. for removed_base_field in removed_base_fields:
  539. dependencies.append((base_app_label, base_name, removed_base_field, False))
  540. # Depend on the other end of the primary key if it's a relation
  541. if primary_key_rel:
  542. dependencies.append((
  543. primary_key_rel._meta.app_label,
  544. primary_key_rel._meta.object_name,
  545. None,
  546. True
  547. ))
  548. # Generate creation operation
  549. self.add_operation(
  550. app_label,
  551. operations.CreateModel(
  552. name=model_state.name,
  553. fields=[d for d in model_state.fields.items() if d[0] not in related_fields],
  554. options=model_state.options,
  555. bases=model_state.bases,
  556. managers=model_state.managers,
  557. ),
  558. dependencies=dependencies,
  559. beginning=True,
  560. )
  561. # Don't add operations which modify the database for unmanaged models
  562. if not model_opts.managed:
  563. continue
  564. # Generate operations for each related field
  565. for name, field in sorted(related_fields.items()):
  566. dependencies = self._get_dependencies_for_foreign_key(field)
  567. # Depend on our own model being created
  568. dependencies.append((app_label, model_name, None, True))
  569. # Make operation
  570. self.add_operation(
  571. app_label,
  572. operations.AddField(
  573. model_name=model_name,
  574. name=name,
  575. field=field,
  576. ),
  577. dependencies=list(set(dependencies)),
  578. )
  579. # Generate other opns
  580. related_dependencies = [
  581. (app_label, model_name, name, True)
  582. for name in sorted(related_fields)
  583. ]
  584. related_dependencies.append((app_label, model_name, None, True))
  585. for index in indexes:
  586. self.add_operation(
  587. app_label,
  588. operations.AddIndex(
  589. model_name=model_name,
  590. index=index,
  591. ),
  592. dependencies=related_dependencies,
  593. )
  594. for constraint in constraints:
  595. self.add_operation(
  596. app_label,
  597. operations.AddConstraint(
  598. model_name=model_name,
  599. constraint=constraint,
  600. ),
  601. dependencies=related_dependencies,
  602. )
  603. if unique_together:
  604. self.add_operation(
  605. app_label,
  606. operations.AlterUniqueTogether(
  607. name=model_name,
  608. unique_together=unique_together,
  609. ),
  610. dependencies=related_dependencies
  611. )
  612. if index_together:
  613. self.add_operation(
  614. app_label,
  615. operations.AlterIndexTogether(
  616. name=model_name,
  617. index_together=index_together,
  618. ),
  619. dependencies=related_dependencies
  620. )
  621. if order_with_respect_to:
  622. self.add_operation(
  623. app_label,
  624. operations.AlterOrderWithRespectTo(
  625. name=model_name,
  626. order_with_respect_to=order_with_respect_to,
  627. ),
  628. dependencies=[
  629. (app_label, model_name, order_with_respect_to, True),
  630. (app_label, model_name, None, True),
  631. ]
  632. )
  633. # Fix relationships if the model changed from a proxy model to a
  634. # concrete model.
  635. if (app_label, model_name) in self.old_proxy_keys:
  636. for related_object in model_opts.related_objects:
  637. self.add_operation(
  638. related_object.related_model._meta.app_label,
  639. operations.AlterField(
  640. model_name=related_object.related_model._meta.object_name,
  641. name=related_object.field.name,
  642. field=related_object.field,
  643. ),
  644. dependencies=[(app_label, model_name, None, True)],
  645. )
  646. def generate_created_proxies(self):
  647. """
  648. Make CreateModel statements for proxy models. Use the same statements
  649. as that way there's less code duplication, but for proxy models it's
  650. safe to skip all the pointless field stuff and chuck out an operation.
  651. """
  652. added = self.new_proxy_keys - self.old_proxy_keys
  653. for app_label, model_name in sorted(added):
  654. model_state = self.to_state.models[app_label, model_name]
  655. assert model_state.options.get("proxy")
  656. # Depend on the deletion of any possible non-proxy version of us
  657. dependencies = [
  658. (app_label, model_name, None, False),
  659. ]
  660. # Depend on all bases
  661. for base in model_state.bases:
  662. if isinstance(base, str) and "." in base:
  663. base_app_label, base_name = base.split(".", 1)
  664. dependencies.append((base_app_label, base_name, None, True))
  665. # Generate creation operation
  666. self.add_operation(
  667. app_label,
  668. operations.CreateModel(
  669. name=model_state.name,
  670. fields=[],
  671. options=model_state.options,
  672. bases=model_state.bases,
  673. managers=model_state.managers,
  674. ),
  675. # Depend on the deletion of any possible non-proxy version of us
  676. dependencies=dependencies,
  677. )
  678. def generate_deleted_models(self):
  679. """
  680. Find all deleted models (managed and unmanaged) and make delete
  681. operations for them as well as separate operations to delete any
  682. foreign key or M2M relationships (these are optimized later, if
  683. possible).
  684. Also bring forward removal of any model options that refer to
  685. collections of fields - the inverse of generate_created_models().
  686. """
  687. new_keys = self.new_model_keys | self.new_unmanaged_keys
  688. deleted_models = self.old_model_keys - new_keys
  689. deleted_unmanaged_models = self.old_unmanaged_keys - new_keys
  690. all_deleted_models = chain(sorted(deleted_models), sorted(deleted_unmanaged_models))
  691. for app_label, model_name in all_deleted_models:
  692. model_state = self.from_state.models[app_label, model_name]
  693. model = self.old_apps.get_model(app_label, model_name)
  694. # Gather related fields
  695. related_fields = {}
  696. for field in model._meta.local_fields:
  697. if field.remote_field:
  698. if field.remote_field.model:
  699. related_fields[field.name] = field
  700. # through will be none on M2Ms on swapped-out models;
  701. # we can treat lack of through as auto_created=True, though.
  702. if (getattr(field.remote_field, "through", None) and
  703. not field.remote_field.through._meta.auto_created):
  704. related_fields[field.name] = field
  705. for field in model._meta.local_many_to_many:
  706. if field.remote_field.model:
  707. related_fields[field.name] = field
  708. if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
  709. related_fields[field.name] = field
  710. # Generate option removal first
  711. unique_together = model_state.options.pop('unique_together', None)
  712. index_together = model_state.options.pop('index_together', None)
  713. if unique_together:
  714. self.add_operation(
  715. app_label,
  716. operations.AlterUniqueTogether(
  717. name=model_name,
  718. unique_together=None,
  719. )
  720. )
  721. if index_together:
  722. self.add_operation(
  723. app_label,
  724. operations.AlterIndexTogether(
  725. name=model_name,
  726. index_together=None,
  727. )
  728. )
  729. # Then remove each related field
  730. for name in sorted(related_fields):
  731. self.add_operation(
  732. app_label,
  733. operations.RemoveField(
  734. model_name=model_name,
  735. name=name,
  736. )
  737. )
  738. # Finally, remove the model.
  739. # This depends on both the removal/alteration of all incoming fields
  740. # and the removal of all its own related fields, and if it's
  741. # a through model the field that references it.
  742. dependencies = []
  743. for related_object in model._meta.related_objects:
  744. related_object_app_label = related_object.related_model._meta.app_label
  745. object_name = related_object.related_model._meta.object_name
  746. field_name = related_object.field.name
  747. dependencies.append((related_object_app_label, object_name, field_name, False))
  748. if not related_object.many_to_many:
  749. dependencies.append((related_object_app_label, object_name, field_name, "alter"))
  750. for name in sorted(related_fields):
  751. dependencies.append((app_label, model_name, name, False))
  752. # We're referenced in another field's through=
  753. through_user = self.through_users.get((app_label, model_state.name_lower))
  754. if through_user:
  755. dependencies.append((through_user[0], through_user[1], through_user[2], False))
  756. # Finally, make the operation, deduping any dependencies
  757. self.add_operation(
  758. app_label,
  759. operations.DeleteModel(
  760. name=model_state.name,
  761. ),
  762. dependencies=list(set(dependencies)),
  763. )
  764. def generate_deleted_proxies(self):
  765. """Make DeleteModel options for proxy models."""
  766. deleted = self.old_proxy_keys - self.new_proxy_keys
  767. for app_label, model_name in sorted(deleted):
  768. model_state = self.from_state.models[app_label, model_name]
  769. assert model_state.options.get("proxy")
  770. self.add_operation(
  771. app_label,
  772. operations.DeleteModel(
  773. name=model_state.name,
  774. ),
  775. )
  776. def generate_renamed_fields(self):
  777. """Work out renamed fields."""
  778. self.renamed_fields = {}
  779. for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
  780. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  781. old_model_state = self.from_state.models[app_label, old_model_name]
  782. field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  783. # Scan to see if this is actually a rename!
  784. field_dec = self.deep_deconstruct(field)
  785. for rem_app_label, rem_model_name, rem_field_name in sorted(self.old_field_keys - self.new_field_keys):
  786. if rem_app_label == app_label and rem_model_name == model_name:
  787. old_field = old_model_state.fields[rem_field_name]
  788. old_field_dec = self.deep_deconstruct(old_field)
  789. if field.remote_field and field.remote_field.model and 'to' in old_field_dec[2]:
  790. old_rel_to = old_field_dec[2]['to']
  791. if old_rel_to in self.renamed_models_rel:
  792. old_field_dec[2]['to'] = self.renamed_models_rel[old_rel_to]
  793. old_field.set_attributes_from_name(rem_field_name)
  794. old_db_column = old_field.get_attname_column()[1]
  795. if (old_field_dec == field_dec or (
  796. # Was the field renamed and db_column equal to the
  797. # old field's column added?
  798. old_field_dec[0:2] == field_dec[0:2] and
  799. dict(old_field_dec[2], db_column=old_db_column) == field_dec[2])):
  800. if self.questioner.ask_rename(model_name, rem_field_name, field_name, field):
  801. self.add_operation(
  802. app_label,
  803. operations.RenameField(
  804. model_name=model_name,
  805. old_name=rem_field_name,
  806. new_name=field_name,
  807. )
  808. )
  809. self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name))
  810. self.old_field_keys.add((app_label, model_name, field_name))
  811. self.renamed_fields[app_label, model_name, field_name] = rem_field_name
  812. break
  813. def generate_added_fields(self):
  814. """Make AddField operations."""
  815. for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
  816. self._generate_added_field(app_label, model_name, field_name)
  817. def _generate_added_field(self, app_label, model_name, field_name):
  818. field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  819. # Fields that are foreignkeys/m2ms depend on stuff
  820. dependencies = []
  821. if field.remote_field and field.remote_field.model:
  822. dependencies.extend(self._get_dependencies_for_foreign_key(field))
  823. # You can't just add NOT NULL fields with no default or fields
  824. # which don't allow empty strings as default.
  825. time_fields = (models.DateField, models.DateTimeField, models.TimeField)
  826. preserve_default = (
  827. field.null or field.has_default() or field.many_to_many or
  828. (field.blank and field.empty_strings_allowed) or
  829. (isinstance(field, time_fields) and field.auto_now)
  830. )
  831. if not preserve_default:
  832. field = field.clone()
  833. if isinstance(field, time_fields) and field.auto_now_add:
  834. field.default = self.questioner.ask_auto_now_add_addition(field_name, model_name)
  835. else:
  836. field.default = self.questioner.ask_not_null_addition(field_name, model_name)
  837. self.add_operation(
  838. app_label,
  839. operations.AddField(
  840. model_name=model_name,
  841. name=field_name,
  842. field=field,
  843. preserve_default=preserve_default,
  844. ),
  845. dependencies=dependencies,
  846. )
  847. def generate_removed_fields(self):
  848. """Make RemoveField operations."""
  849. for app_label, model_name, field_name in sorted(self.old_field_keys - self.new_field_keys):
  850. self._generate_removed_field(app_label, model_name, field_name)
  851. def _generate_removed_field(self, app_label, model_name, field_name):
  852. self.add_operation(
  853. app_label,
  854. operations.RemoveField(
  855. model_name=model_name,
  856. name=field_name,
  857. ),
  858. # We might need to depend on the removal of an
  859. # order_with_respect_to or index/unique_together operation;
  860. # this is safely ignored if there isn't one
  861. dependencies=[
  862. (app_label, model_name, field_name, "order_wrt_unset"),
  863. (app_label, model_name, field_name, "foo_together_change"),
  864. ],
  865. )
  866. def generate_altered_fields(self):
  867. """
  868. Make AlterField operations, or possibly RemovedField/AddField if alter
  869. isn's possible.
  870. """
  871. for app_label, model_name, field_name in sorted(self.old_field_keys & self.new_field_keys):
  872. # Did the field change?
  873. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  874. old_field_name = self.renamed_fields.get((app_label, model_name, field_name), field_name)
  875. old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field(old_field_name)
  876. new_field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  877. dependencies = []
  878. # Implement any model renames on relations; these are handled by RenameModel
  879. # so we need to exclude them from the comparison
  880. if hasattr(new_field, "remote_field") and getattr(new_field.remote_field, "model", None):
  881. rename_key = (
  882. new_field.remote_field.model._meta.app_label,
  883. new_field.remote_field.model._meta.model_name,
  884. )
  885. if rename_key in self.renamed_models:
  886. new_field.remote_field.model = old_field.remote_field.model
  887. # Handle ForeignKey which can only have a single to_field.
  888. remote_field_name = getattr(new_field.remote_field, 'field_name', None)
  889. if remote_field_name:
  890. to_field_rename_key = rename_key + (remote_field_name,)
  891. if to_field_rename_key in self.renamed_fields:
  892. # Repoint both model and field name because to_field
  893. # inclusion in ForeignKey.deconstruct() is based on
  894. # both.
  895. new_field.remote_field.model = old_field.remote_field.model
  896. new_field.remote_field.field_name = old_field.remote_field.field_name
  897. # Handle ForeignObjects which can have multiple from_fields/to_fields.
  898. from_fields = getattr(new_field, 'from_fields', None)
  899. if from_fields:
  900. from_rename_key = (app_label, model_name)
  901. new_field.from_fields = tuple([
  902. self.renamed_fields.get(from_rename_key + (from_field,), from_field)
  903. for from_field in from_fields
  904. ])
  905. new_field.to_fields = tuple([
  906. self.renamed_fields.get(rename_key + (to_field,), to_field)
  907. for to_field in new_field.to_fields
  908. ])
  909. dependencies.extend(self._get_dependencies_for_foreign_key(new_field))
  910. if hasattr(new_field, "remote_field") and getattr(new_field.remote_field, "through", None):
  911. rename_key = (
  912. new_field.remote_field.through._meta.app_label,
  913. new_field.remote_field.through._meta.model_name,
  914. )
  915. if rename_key in self.renamed_models:
  916. new_field.remote_field.through = old_field.remote_field.through
  917. old_field_dec = self.deep_deconstruct(old_field)
  918. new_field_dec = self.deep_deconstruct(new_field)
  919. if old_field_dec != new_field_dec:
  920. both_m2m = old_field.many_to_many and new_field.many_to_many
  921. neither_m2m = not old_field.many_to_many and not new_field.many_to_many
  922. if both_m2m or neither_m2m:
  923. # Either both fields are m2m or neither is
  924. preserve_default = True
  925. if (old_field.null and not new_field.null and not new_field.has_default() and
  926. not new_field.many_to_many):
  927. field = new_field.clone()
  928. new_default = self.questioner.ask_not_null_alteration(field_name, model_name)
  929. if new_default is not models.NOT_PROVIDED:
  930. field.default = new_default
  931. preserve_default = False
  932. else:
  933. field = new_field
  934. self.add_operation(
  935. app_label,
  936. operations.AlterField(
  937. model_name=model_name,
  938. name=field_name,
  939. field=field,
  940. preserve_default=preserve_default,
  941. ),
  942. dependencies=dependencies,
  943. )
  944. else:
  945. # We cannot alter between m2m and concrete fields
  946. self._generate_removed_field(app_label, model_name, field_name)
  947. self._generate_added_field(app_label, model_name, field_name)
  948. def create_altered_indexes(self):
  949. option_name = operations.AddIndex.option_name
  950. for app_label, model_name in sorted(self.kept_model_keys):
  951. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  952. old_model_state = self.from_state.models[app_label, old_model_name]
  953. new_model_state = self.to_state.models[app_label, model_name]
  954. old_indexes = old_model_state.options[option_name]
  955. new_indexes = new_model_state.options[option_name]
  956. add_idx = [idx for idx in new_indexes if idx not in old_indexes]
  957. rem_idx = [idx for idx in old_indexes if idx not in new_indexes]
  958. self.altered_indexes.update({
  959. (app_label, model_name): {
  960. 'added_indexes': add_idx, 'removed_indexes': rem_idx,
  961. }
  962. })
  963. def generate_added_indexes(self):
  964. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  965. for index in alt_indexes['added_indexes']:
  966. self.add_operation(
  967. app_label,
  968. operations.AddIndex(
  969. model_name=model_name,
  970. index=index,
  971. )
  972. )
  973. def generate_removed_indexes(self):
  974. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  975. for index in alt_indexes['removed_indexes']:
  976. self.add_operation(
  977. app_label,
  978. operations.RemoveIndex(
  979. model_name=model_name,
  980. name=index.name,
  981. )
  982. )
  983. def create_altered_constraints(self):
  984. option_name = operations.AddConstraint.option_name
  985. for app_label, model_name in sorted(self.kept_model_keys):
  986. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  987. old_model_state = self.from_state.models[app_label, old_model_name]
  988. new_model_state = self.to_state.models[app_label, model_name]
  989. old_constraints = old_model_state.options[option_name]
  990. new_constraints = new_model_state.options[option_name]
  991. add_constraints = [c for c in new_constraints if c not in old_constraints]
  992. rem_constraints = [c for c in old_constraints if c not in new_constraints]
  993. self.altered_constraints.update({
  994. (app_label, model_name): {
  995. 'added_constraints': add_constraints, 'removed_constraints': rem_constraints,
  996. }
  997. })
  998. def generate_added_constraints(self):
  999. for (app_label, model_name), alt_constraints in self.altered_constraints.items():
  1000. for constraint in alt_constraints['added_constraints']:
  1001. self.add_operation(
  1002. app_label,
  1003. operations.AddConstraint(
  1004. model_name=model_name,
  1005. constraint=constraint,
  1006. )
  1007. )
  1008. def generate_removed_constraints(self):
  1009. for (app_label, model_name), alt_constraints in self.altered_constraints.items():
  1010. for constraint in alt_constraints['removed_constraints']:
  1011. self.add_operation(
  1012. app_label,
  1013. operations.RemoveConstraint(
  1014. model_name=model_name,
  1015. name=constraint.name,
  1016. )
  1017. )
  1018. def _get_dependencies_for_foreign_key(self, field):
  1019. # Account for FKs to swappable models
  1020. swappable_setting = getattr(field, 'swappable_setting', None)
  1021. if swappable_setting is not None:
  1022. dep_app_label = "__setting__"
  1023. dep_object_name = swappable_setting
  1024. else:
  1025. dep_app_label = field.remote_field.model._meta.app_label
  1026. dep_object_name = field.remote_field.model._meta.object_name
  1027. dependencies = [(dep_app_label, dep_object_name, None, True)]
  1028. if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created:
  1029. dependencies.append((
  1030. field.remote_field.through._meta.app_label,
  1031. field.remote_field.through._meta.object_name,
  1032. None,
  1033. True,
  1034. ))
  1035. return dependencies
  1036. def _generate_altered_foo_together(self, operation):
  1037. option_name = operation.option_name
  1038. for app_label, model_name in sorted(self.kept_model_keys):
  1039. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1040. old_model_state = self.from_state.models[app_label, old_model_name]
  1041. new_model_state = self.to_state.models[app_label, model_name]
  1042. # We run the old version through the field renames to account for those
  1043. old_value = old_model_state.options.get(option_name)
  1044. old_value = {
  1045. tuple(
  1046. self.renamed_fields.get((app_label, model_name, n), n)
  1047. for n in unique
  1048. )
  1049. for unique in old_value
  1050. } if old_value else set()
  1051. new_value = new_model_state.options.get(option_name)
  1052. new_value = set(new_value) if new_value else set()
  1053. if old_value != new_value:
  1054. dependencies = []
  1055. for foo_togethers in new_value:
  1056. for field_name in foo_togethers:
  1057. field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
  1058. if field.remote_field and field.remote_field.model:
  1059. dependencies.extend(self._get_dependencies_for_foreign_key(field))
  1060. self.add_operation(
  1061. app_label,
  1062. operation(
  1063. name=model_name,
  1064. **{option_name: new_value}
  1065. ),
  1066. dependencies=dependencies,
  1067. )
  1068. def generate_altered_unique_together(self):
  1069. self._generate_altered_foo_together(operations.AlterUniqueTogether)
  1070. def generate_altered_index_together(self):
  1071. self._generate_altered_foo_together(operations.AlterIndexTogether)
  1072. def generate_altered_db_table(self):
  1073. models_to_check = self.kept_model_keys.union(self.kept_proxy_keys, self.kept_unmanaged_keys)
  1074. for app_label, model_name in sorted(models_to_check):
  1075. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1076. old_model_state = self.from_state.models[app_label, old_model_name]
  1077. new_model_state = self.to_state.models[app_label, model_name]
  1078. old_db_table_name = old_model_state.options.get('db_table')
  1079. new_db_table_name = new_model_state.options.get('db_table')
  1080. if old_db_table_name != new_db_table_name:
  1081. self.add_operation(
  1082. app_label,
  1083. operations.AlterModelTable(
  1084. name=model_name,
  1085. table=new_db_table_name,
  1086. )
  1087. )
  1088. def generate_altered_options(self):
  1089. """
  1090. Work out if any non-schema-affecting options have changed and make an
  1091. operation to represent them in state changes (in case Python code in
  1092. migrations needs them).
  1093. """
  1094. models_to_check = self.kept_model_keys.union(
  1095. self.kept_proxy_keys,
  1096. self.kept_unmanaged_keys,
  1097. # unmanaged converted to managed
  1098. self.old_unmanaged_keys & self.new_model_keys,
  1099. # managed converted to unmanaged
  1100. self.old_model_keys & self.new_unmanaged_keys,
  1101. )
  1102. for app_label, model_name in sorted(models_to_check):
  1103. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1104. old_model_state = self.from_state.models[app_label, old_model_name]
  1105. new_model_state = self.to_state.models[app_label, model_name]
  1106. old_options = {
  1107. key: value for key, value in old_model_state.options.items()
  1108. if key in AlterModelOptions.ALTER_OPTION_KEYS
  1109. }
  1110. new_options = {
  1111. key: value for key, value in new_model_state.options.items()
  1112. if key in AlterModelOptions.ALTER_OPTION_KEYS
  1113. }
  1114. if old_options != new_options:
  1115. self.add_operation(
  1116. app_label,
  1117. operations.AlterModelOptions(
  1118. name=model_name,
  1119. options=new_options,
  1120. )
  1121. )
  1122. def generate_altered_order_with_respect_to(self):
  1123. for app_label, model_name in sorted(self.kept_model_keys):
  1124. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1125. old_model_state = self.from_state.models[app_label, old_model_name]
  1126. new_model_state = self.to_state.models[app_label, model_name]
  1127. if (old_model_state.options.get("order_with_respect_to") !=
  1128. new_model_state.options.get("order_with_respect_to")):
  1129. # Make sure it comes second if we're adding
  1130. # (removal dependency is part of RemoveField)
  1131. dependencies = []
  1132. if new_model_state.options.get("order_with_respect_to"):
  1133. dependencies.append((
  1134. app_label,
  1135. model_name,
  1136. new_model_state.options["order_with_respect_to"],
  1137. True,
  1138. ))
  1139. # Actually generate the operation
  1140. self.add_operation(
  1141. app_label,
  1142. operations.AlterOrderWithRespectTo(
  1143. name=model_name,
  1144. order_with_respect_to=new_model_state.options.get('order_with_respect_to'),
  1145. ),
  1146. dependencies=dependencies,
  1147. )
  1148. def generate_altered_managers(self):
  1149. for app_label, model_name in sorted(self.kept_model_keys):
  1150. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  1151. old_model_state = self.from_state.models[app_label, old_model_name]
  1152. new_model_state = self.to_state.models[app_label, model_name]
  1153. if old_model_state.managers != new_model_state.managers:
  1154. self.add_operation(
  1155. app_label,
  1156. operations.AlterModelManagers(
  1157. name=model_name,
  1158. managers=new_model_state.managers,
  1159. )
  1160. )
  1161. def arrange_for_graph(self, changes, graph, migration_name=None):
  1162. """
  1163. Take a result from changes() and a MigrationGraph, and fix the names
  1164. and dependencies of the changes so they extend the graph from the leaf
  1165. nodes for each app.
  1166. """
  1167. leaves = graph.leaf_nodes()
  1168. name_map = {}
  1169. for app_label, migrations in list(changes.items()):
  1170. if not migrations:
  1171. continue
  1172. # Find the app label's current leaf node
  1173. app_leaf = None
  1174. for leaf in leaves:
  1175. if leaf[0] == app_label:
  1176. app_leaf = leaf
  1177. break
  1178. # Do they want an initial migration for this app?
  1179. if app_leaf is None and not self.questioner.ask_initial(app_label):
  1180. # They don't.
  1181. for migration in migrations:
  1182. name_map[(app_label, migration.name)] = (app_label, "__first__")
  1183. del changes[app_label]
  1184. continue
  1185. # Work out the next number in the sequence
  1186. if app_leaf is None:
  1187. next_number = 1
  1188. else:
  1189. next_number = (self.parse_number(app_leaf[1]) or 0) + 1
  1190. # Name each migration
  1191. for i, migration in enumerate(migrations):
  1192. if i == 0 and app_leaf:
  1193. migration.dependencies.append(app_leaf)
  1194. if i == 0 and not app_leaf:
  1195. new_name = "0001_%s" % migration_name if migration_name else "0001_initial"
  1196. else:
  1197. new_name = "%04i_%s" % (
  1198. next_number,
  1199. migration_name or self.suggest_name(migration.operations)[:100],
  1200. )
  1201. name_map[(app_label, migration.name)] = (app_label, new_name)
  1202. next_number += 1
  1203. migration.name = new_name
  1204. # Now fix dependencies
  1205. for migrations in changes.values():
  1206. for migration in migrations:
  1207. migration.dependencies = [name_map.get(d, d) for d in migration.dependencies]
  1208. return changes
  1209. def _trim_to_apps(self, changes, app_labels):
  1210. """
  1211. Take changes from arrange_for_graph() and set of app labels, and return
  1212. a modified set of changes which trims out as many migrations that are
  1213. not in app_labels as possible. Note that some other migrations may
  1214. still be present as they may be required dependencies.
  1215. """
  1216. # Gather other app dependencies in a first pass
  1217. app_dependencies = {}
  1218. for app_label, migrations in changes.items():
  1219. for migration in migrations:
  1220. for dep_app_label, name in migration.dependencies:
  1221. app_dependencies.setdefault(app_label, set()).add(dep_app_label)
  1222. required_apps = set(app_labels)
  1223. # Keep resolving till there's no change
  1224. old_required_apps = None
  1225. while old_required_apps != required_apps:
  1226. old_required_apps = set(required_apps)
  1227. required_apps.update(*[app_dependencies.get(app_label, ()) for app_label in required_apps])
  1228. # Remove all migrations that aren't needed
  1229. for app_label in list(changes):
  1230. if app_label not in required_apps:
  1231. del changes[app_label]
  1232. return changes
  1233. @classmethod
  1234. def suggest_name(cls, ops):
  1235. """
  1236. Given a set of operations, suggest a name for the migration they might
  1237. represent. Names are not guaranteed to be unique, but put some effort
  1238. into the fallback name to avoid VCS conflicts if possible.
  1239. """
  1240. name = None
  1241. if len(ops) == 1:
  1242. name = ops[0].migration_name_fragment
  1243. elif len(ops) > 1 and all(isinstance(o, operations.CreateModel) for o in ops):
  1244. name = '_'.join(sorted(o.migration_name_fragment for o in ops))
  1245. if name is None:
  1246. name = 'auto_%s' % get_migration_name_timestamp()
  1247. return name
  1248. @classmethod
  1249. def parse_number(cls, name):
  1250. """
  1251. Given a migration name, try to extract a number from the beginning of
  1252. it. If no number is found, return None.
  1253. """
  1254. match = re.match(r'^\d+', name)
  1255. if match:
  1256. return int(match[0])
  1257. return None