models.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. from django.db import models
  2. from django.db.migrations.operations.base import Operation
  3. from django.db.migrations.state import ModelState
  4. from django.db.migrations.utils import field_references, resolve_relation
  5. from django.db.models.options import normalize_together
  6. from django.utils.functional import cached_property
  7. from .fields import AddField, AlterField, FieldOperation, RemoveField, RenameField
  8. def _check_for_duplicates(arg_name, objs):
  9. used_vals = set()
  10. for val in objs:
  11. if val in used_vals:
  12. raise ValueError(
  13. "Found duplicate value %s in CreateModel %s argument." % (val, arg_name)
  14. )
  15. used_vals.add(val)
  16. class ModelOperation(Operation):
  17. def __init__(self, name):
  18. self.name = name
  19. @cached_property
  20. def name_lower(self):
  21. return self.name.lower()
  22. def references_model(self, name, app_label):
  23. return name.lower() == self.name_lower
  24. def reduce(self, operation, app_label):
  25. return super().reduce(operation, app_label) or self.can_reduce_through(
  26. operation, app_label
  27. )
  28. def can_reduce_through(self, operation, app_label):
  29. return not operation.references_model(self.name, app_label)
  30. class CreateModel(ModelOperation):
  31. """Create a model's table."""
  32. serialization_expand_args = ["fields", "options", "managers"]
  33. def __init__(self, name, fields, options=None, bases=None, managers=None):
  34. self.fields = fields
  35. self.options = options or {}
  36. self.bases = bases or (models.Model,)
  37. self.managers = managers or []
  38. super().__init__(name)
  39. # Sanity-check that there are no duplicated field names, bases, or
  40. # manager names
  41. _check_for_duplicates("fields", (name for name, _ in self.fields))
  42. _check_for_duplicates(
  43. "bases",
  44. (
  45. base._meta.label_lower
  46. if hasattr(base, "_meta")
  47. else base.lower()
  48. if isinstance(base, str)
  49. else base
  50. for base in self.bases
  51. ),
  52. )
  53. _check_for_duplicates("managers", (name for name, _ in self.managers))
  54. def deconstruct(self):
  55. kwargs = {
  56. "name": self.name,
  57. "fields": self.fields,
  58. }
  59. if self.options:
  60. kwargs["options"] = self.options
  61. if self.bases and self.bases != (models.Model,):
  62. kwargs["bases"] = self.bases
  63. if self.managers and self.managers != [("objects", models.Manager())]:
  64. kwargs["managers"] = self.managers
  65. return (self.__class__.__qualname__, [], kwargs)
  66. def state_forwards(self, app_label, state):
  67. state.add_model(
  68. ModelState(
  69. app_label,
  70. self.name,
  71. list(self.fields),
  72. dict(self.options),
  73. tuple(self.bases),
  74. list(self.managers),
  75. )
  76. )
  77. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  78. model = to_state.apps.get_model(app_label, self.name)
  79. if self.allow_migrate_model(schema_editor.connection.alias, model):
  80. schema_editor.create_model(model)
  81. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  82. model = from_state.apps.get_model(app_label, self.name)
  83. if self.allow_migrate_model(schema_editor.connection.alias, model):
  84. schema_editor.delete_model(model)
  85. def describe(self):
  86. return "Create %smodel %s" % (
  87. "proxy " if self.options.get("proxy", False) else "",
  88. self.name,
  89. )
  90. @property
  91. def migration_name_fragment(self):
  92. return self.name_lower
  93. def references_model(self, name, app_label):
  94. name_lower = name.lower()
  95. if name_lower == self.name_lower:
  96. return True
  97. # Check we didn't inherit from the model
  98. reference_model_tuple = (app_label, name_lower)
  99. for base in self.bases:
  100. if (
  101. base is not models.Model
  102. and isinstance(base, (models.base.ModelBase, str))
  103. and resolve_relation(base, app_label) == reference_model_tuple
  104. ):
  105. return True
  106. # Check we have no FKs/M2Ms with it
  107. for _name, field in self.fields:
  108. if field_references(
  109. (app_label, self.name_lower), field, reference_model_tuple
  110. ):
  111. return True
  112. return False
  113. def reduce(self, operation, app_label):
  114. if (
  115. isinstance(operation, DeleteModel)
  116. and self.name_lower == operation.name_lower
  117. and not self.options.get("proxy", False)
  118. ):
  119. return []
  120. elif (
  121. isinstance(operation, RenameModel)
  122. and self.name_lower == operation.old_name_lower
  123. ):
  124. return [
  125. CreateModel(
  126. operation.new_name,
  127. fields=self.fields,
  128. options=self.options,
  129. bases=self.bases,
  130. managers=self.managers,
  131. ),
  132. ]
  133. elif (
  134. isinstance(operation, AlterModelOptions)
  135. and self.name_lower == operation.name_lower
  136. ):
  137. options = {**self.options, **operation.options}
  138. for key in operation.ALTER_OPTION_KEYS:
  139. if key not in operation.options:
  140. options.pop(key, None)
  141. return [
  142. CreateModel(
  143. self.name,
  144. fields=self.fields,
  145. options=options,
  146. bases=self.bases,
  147. managers=self.managers,
  148. ),
  149. ]
  150. elif (
  151. isinstance(operation, AlterModelManagers)
  152. and self.name_lower == operation.name_lower
  153. ):
  154. return [
  155. CreateModel(
  156. self.name,
  157. fields=self.fields,
  158. options=self.options,
  159. bases=self.bases,
  160. managers=operation.managers,
  161. ),
  162. ]
  163. elif (
  164. isinstance(operation, AlterTogetherOptionOperation)
  165. and self.name_lower == operation.name_lower
  166. ):
  167. return [
  168. CreateModel(
  169. self.name,
  170. fields=self.fields,
  171. options={
  172. **self.options,
  173. **{operation.option_name: operation.option_value},
  174. },
  175. bases=self.bases,
  176. managers=self.managers,
  177. ),
  178. ]
  179. elif (
  180. isinstance(operation, AlterOrderWithRespectTo)
  181. and self.name_lower == operation.name_lower
  182. ):
  183. return [
  184. CreateModel(
  185. self.name,
  186. fields=self.fields,
  187. options={
  188. **self.options,
  189. "order_with_respect_to": operation.order_with_respect_to,
  190. },
  191. bases=self.bases,
  192. managers=self.managers,
  193. ),
  194. ]
  195. elif (
  196. isinstance(operation, FieldOperation)
  197. and self.name_lower == operation.model_name_lower
  198. ):
  199. if isinstance(operation, AddField):
  200. return [
  201. CreateModel(
  202. self.name,
  203. fields=self.fields + [(operation.name, operation.field)],
  204. options=self.options,
  205. bases=self.bases,
  206. managers=self.managers,
  207. ),
  208. ]
  209. elif isinstance(operation, AlterField):
  210. return [
  211. CreateModel(
  212. self.name,
  213. fields=[
  214. (n, operation.field if n == operation.name else v)
  215. for n, v in self.fields
  216. ],
  217. options=self.options,
  218. bases=self.bases,
  219. managers=self.managers,
  220. ),
  221. ]
  222. elif isinstance(operation, RemoveField):
  223. options = self.options.copy()
  224. for option_name in ("unique_together", "index_together"):
  225. option = options.pop(option_name, None)
  226. if option:
  227. option = set(
  228. filter(
  229. bool,
  230. (
  231. tuple(
  232. f for f in fields if f != operation.name_lower
  233. )
  234. for fields in option
  235. ),
  236. )
  237. )
  238. if option:
  239. options[option_name] = option
  240. order_with_respect_to = options.get("order_with_respect_to")
  241. if order_with_respect_to == operation.name_lower:
  242. del options["order_with_respect_to"]
  243. return [
  244. CreateModel(
  245. self.name,
  246. fields=[
  247. (n, v)
  248. for n, v in self.fields
  249. if n.lower() != operation.name_lower
  250. ],
  251. options=options,
  252. bases=self.bases,
  253. managers=self.managers,
  254. ),
  255. ]
  256. elif isinstance(operation, RenameField):
  257. options = self.options.copy()
  258. for option_name in ("unique_together", "index_together"):
  259. option = options.get(option_name)
  260. if option:
  261. options[option_name] = {
  262. tuple(
  263. operation.new_name if f == operation.old_name else f
  264. for f in fields
  265. )
  266. for fields in option
  267. }
  268. order_with_respect_to = options.get("order_with_respect_to")
  269. if order_with_respect_to == operation.old_name:
  270. options["order_with_respect_to"] = operation.new_name
  271. return [
  272. CreateModel(
  273. self.name,
  274. fields=[
  275. (operation.new_name if n == operation.old_name else n, v)
  276. for n, v in self.fields
  277. ],
  278. options=options,
  279. bases=self.bases,
  280. managers=self.managers,
  281. ),
  282. ]
  283. elif (
  284. isinstance(operation, IndexOperation)
  285. and self.name_lower == operation.model_name_lower
  286. ):
  287. if isinstance(operation, AddIndex):
  288. return [
  289. CreateModel(
  290. self.name,
  291. fields=self.fields,
  292. options={
  293. **self.options,
  294. "indexes": [
  295. *self.options.get("indexes", []),
  296. operation.index,
  297. ],
  298. },
  299. bases=self.bases,
  300. managers=self.managers,
  301. ),
  302. ]
  303. elif isinstance(operation, RemoveIndex):
  304. options_indexes = [
  305. index
  306. for index in self.options.get("indexes", [])
  307. if index.name != operation.name
  308. ]
  309. return [
  310. CreateModel(
  311. self.name,
  312. fields=self.fields,
  313. options={
  314. **self.options,
  315. "indexes": options_indexes,
  316. },
  317. bases=self.bases,
  318. managers=self.managers,
  319. ),
  320. ]
  321. elif isinstance(operation, RenameIndex) and operation.old_fields:
  322. options_index_together = {
  323. fields
  324. for fields in self.options.get("index_together", [])
  325. if fields != operation.old_fields
  326. }
  327. if options_index_together:
  328. self.options["index_together"] = options_index_together
  329. else:
  330. self.options.pop("index_together", None)
  331. return [
  332. CreateModel(
  333. self.name,
  334. fields=self.fields,
  335. options={
  336. **self.options,
  337. "indexes": [
  338. *self.options.get("indexes", []),
  339. models.Index(
  340. fields=operation.old_fields, name=operation.new_name
  341. ),
  342. ],
  343. },
  344. bases=self.bases,
  345. managers=self.managers,
  346. ),
  347. ]
  348. return super().reduce(operation, app_label)
  349. class DeleteModel(ModelOperation):
  350. """Drop a model's table."""
  351. def deconstruct(self):
  352. kwargs = {
  353. "name": self.name,
  354. }
  355. return (self.__class__.__qualname__, [], kwargs)
  356. def state_forwards(self, app_label, state):
  357. state.remove_model(app_label, self.name_lower)
  358. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  359. model = from_state.apps.get_model(app_label, self.name)
  360. if self.allow_migrate_model(schema_editor.connection.alias, model):
  361. schema_editor.delete_model(model)
  362. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  363. model = to_state.apps.get_model(app_label, self.name)
  364. if self.allow_migrate_model(schema_editor.connection.alias, model):
  365. schema_editor.create_model(model)
  366. def references_model(self, name, app_label):
  367. # The deleted model could be referencing the specified model through
  368. # related fields.
  369. return True
  370. def describe(self):
  371. return "Delete model %s" % self.name
  372. @property
  373. def migration_name_fragment(self):
  374. return "delete_%s" % self.name_lower
  375. class RenameModel(ModelOperation):
  376. """Rename a model."""
  377. def __init__(self, old_name, new_name):
  378. self.old_name = old_name
  379. self.new_name = new_name
  380. super().__init__(old_name)
  381. @cached_property
  382. def old_name_lower(self):
  383. return self.old_name.lower()
  384. @cached_property
  385. def new_name_lower(self):
  386. return self.new_name.lower()
  387. def deconstruct(self):
  388. kwargs = {
  389. "old_name": self.old_name,
  390. "new_name": self.new_name,
  391. }
  392. return (self.__class__.__qualname__, [], kwargs)
  393. def state_forwards(self, app_label, state):
  394. state.rename_model(app_label, self.old_name, self.new_name)
  395. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  396. new_model = to_state.apps.get_model(app_label, self.new_name)
  397. if self.allow_migrate_model(schema_editor.connection.alias, new_model):
  398. old_model = from_state.apps.get_model(app_label, self.old_name)
  399. # Move the main table
  400. schema_editor.alter_db_table(
  401. new_model,
  402. old_model._meta.db_table,
  403. new_model._meta.db_table,
  404. )
  405. # Alter the fields pointing to us
  406. for related_object in old_model._meta.related_objects:
  407. if related_object.related_model == old_model:
  408. model = new_model
  409. related_key = (app_label, self.new_name_lower)
  410. else:
  411. model = related_object.related_model
  412. related_key = (
  413. related_object.related_model._meta.app_label,
  414. related_object.related_model._meta.model_name,
  415. )
  416. to_field = to_state.apps.get_model(*related_key)._meta.get_field(
  417. related_object.field.name
  418. )
  419. schema_editor.alter_field(
  420. model,
  421. related_object.field,
  422. to_field,
  423. )
  424. # Rename M2M fields whose name is based on this model's name.
  425. fields = zip(
  426. old_model._meta.local_many_to_many, new_model._meta.local_many_to_many
  427. )
  428. for old_field, new_field in fields:
  429. # Skip self-referential fields as these are renamed above.
  430. if (
  431. new_field.model == new_field.related_model
  432. or not new_field.remote_field.through._meta.auto_created
  433. ):
  434. continue
  435. # Rename columns and the M2M table.
  436. schema_editor._alter_many_to_many(
  437. new_model,
  438. old_field,
  439. new_field,
  440. strict=False,
  441. )
  442. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  443. self.new_name_lower, self.old_name_lower = (
  444. self.old_name_lower,
  445. self.new_name_lower,
  446. )
  447. self.new_name, self.old_name = self.old_name, self.new_name
  448. self.database_forwards(app_label, schema_editor, from_state, to_state)
  449. self.new_name_lower, self.old_name_lower = (
  450. self.old_name_lower,
  451. self.new_name_lower,
  452. )
  453. self.new_name, self.old_name = self.old_name, self.new_name
  454. def references_model(self, name, app_label):
  455. return (
  456. name.lower() == self.old_name_lower or name.lower() == self.new_name_lower
  457. )
  458. def describe(self):
  459. return "Rename model %s to %s" % (self.old_name, self.new_name)
  460. @property
  461. def migration_name_fragment(self):
  462. return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower)
  463. def reduce(self, operation, app_label):
  464. if (
  465. isinstance(operation, RenameModel)
  466. and self.new_name_lower == operation.old_name_lower
  467. ):
  468. return [
  469. RenameModel(
  470. self.old_name,
  471. operation.new_name,
  472. ),
  473. ]
  474. # Skip `ModelOperation.reduce` as we want to run `references_model`
  475. # against self.new_name.
  476. return super(ModelOperation, self).reduce(
  477. operation, app_label
  478. ) or not operation.references_model(self.new_name, app_label)
  479. class ModelOptionOperation(ModelOperation):
  480. def reduce(self, operation, app_label):
  481. if (
  482. isinstance(operation, (self.__class__, DeleteModel))
  483. and self.name_lower == operation.name_lower
  484. ):
  485. return [operation]
  486. return super().reduce(operation, app_label)
  487. class AlterModelTable(ModelOptionOperation):
  488. """Rename a model's table."""
  489. def __init__(self, name, table):
  490. self.table = table
  491. super().__init__(name)
  492. def deconstruct(self):
  493. kwargs = {
  494. "name": self.name,
  495. "table": self.table,
  496. }
  497. return (self.__class__.__qualname__, [], kwargs)
  498. def state_forwards(self, app_label, state):
  499. state.alter_model_options(app_label, self.name_lower, {"db_table": self.table})
  500. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  501. new_model = to_state.apps.get_model(app_label, self.name)
  502. if self.allow_migrate_model(schema_editor.connection.alias, new_model):
  503. old_model = from_state.apps.get_model(app_label, self.name)
  504. schema_editor.alter_db_table(
  505. new_model,
  506. old_model._meta.db_table,
  507. new_model._meta.db_table,
  508. )
  509. # Rename M2M fields whose name is based on this model's db_table
  510. for old_field, new_field in zip(
  511. old_model._meta.local_many_to_many, new_model._meta.local_many_to_many
  512. ):
  513. if new_field.remote_field.through._meta.auto_created:
  514. schema_editor.alter_db_table(
  515. new_field.remote_field.through,
  516. old_field.remote_field.through._meta.db_table,
  517. new_field.remote_field.through._meta.db_table,
  518. )
  519. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  520. return self.database_forwards(app_label, schema_editor, from_state, to_state)
  521. def describe(self):
  522. return "Rename table for %s to %s" % (
  523. self.name,
  524. self.table if self.table is not None else "(default)",
  525. )
  526. @property
  527. def migration_name_fragment(self):
  528. return "alter_%s_table" % self.name_lower
  529. class AlterModelTableComment(ModelOptionOperation):
  530. def __init__(self, name, table_comment):
  531. self.table_comment = table_comment
  532. super().__init__(name)
  533. def deconstruct(self):
  534. kwargs = {
  535. "name": self.name,
  536. "table_comment": self.table_comment,
  537. }
  538. return (self.__class__.__qualname__, [], kwargs)
  539. def state_forwards(self, app_label, state):
  540. state.alter_model_options(
  541. app_label, self.name_lower, {"db_table_comment": self.table_comment}
  542. )
  543. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  544. new_model = to_state.apps.get_model(app_label, self.name)
  545. if self.allow_migrate_model(schema_editor.connection.alias, new_model):
  546. old_model = from_state.apps.get_model(app_label, self.name)
  547. schema_editor.alter_db_table_comment(
  548. new_model,
  549. old_model._meta.db_table_comment,
  550. new_model._meta.db_table_comment,
  551. )
  552. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  553. return self.database_forwards(app_label, schema_editor, from_state, to_state)
  554. def describe(self):
  555. return f"Alter {self.name} table comment"
  556. @property
  557. def migration_name_fragment(self):
  558. return f"alter_{self.name_lower}_table_comment"
  559. class AlterTogetherOptionOperation(ModelOptionOperation):
  560. option_name = None
  561. def __init__(self, name, option_value):
  562. if option_value:
  563. option_value = set(normalize_together(option_value))
  564. setattr(self, self.option_name, option_value)
  565. super().__init__(name)
  566. @cached_property
  567. def option_value(self):
  568. return getattr(self, self.option_name)
  569. def deconstruct(self):
  570. kwargs = {
  571. "name": self.name,
  572. self.option_name: self.option_value,
  573. }
  574. return (self.__class__.__qualname__, [], kwargs)
  575. def state_forwards(self, app_label, state):
  576. state.alter_model_options(
  577. app_label,
  578. self.name_lower,
  579. {self.option_name: self.option_value},
  580. )
  581. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  582. new_model = to_state.apps.get_model(app_label, self.name)
  583. if self.allow_migrate_model(schema_editor.connection.alias, new_model):
  584. old_model = from_state.apps.get_model(app_label, self.name)
  585. alter_together = getattr(schema_editor, "alter_%s" % self.option_name)
  586. alter_together(
  587. new_model,
  588. getattr(old_model._meta, self.option_name, set()),
  589. getattr(new_model._meta, self.option_name, set()),
  590. )
  591. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  592. return self.database_forwards(app_label, schema_editor, from_state, to_state)
  593. def references_field(self, model_name, name, app_label):
  594. return self.references_model(model_name, app_label) and (
  595. not self.option_value
  596. or any((name in fields) for fields in self.option_value)
  597. )
  598. def describe(self):
  599. return "Alter %s for %s (%s constraint(s))" % (
  600. self.option_name,
  601. self.name,
  602. len(self.option_value or ""),
  603. )
  604. @property
  605. def migration_name_fragment(self):
  606. return "alter_%s_%s" % (self.name_lower, self.option_name)
  607. def can_reduce_through(self, operation, app_label):
  608. return super().can_reduce_through(operation, app_label) or (
  609. isinstance(operation, AlterTogetherOptionOperation)
  610. and type(operation) is not type(self)
  611. )
  612. class AlterUniqueTogether(AlterTogetherOptionOperation):
  613. """
  614. Change the value of unique_together to the target one.
  615. Input value of unique_together must be a set of tuples.
  616. """
  617. option_name = "unique_together"
  618. def __init__(self, name, unique_together):
  619. super().__init__(name, unique_together)
  620. class AlterIndexTogether(AlterTogetherOptionOperation):
  621. """
  622. Change the value of index_together to the target one.
  623. Input value of index_together must be a set of tuples.
  624. """
  625. option_name = "index_together"
  626. def __init__(self, name, index_together):
  627. super().__init__(name, index_together)
  628. class AlterOrderWithRespectTo(ModelOptionOperation):
  629. """Represent a change with the order_with_respect_to option."""
  630. option_name = "order_with_respect_to"
  631. def __init__(self, name, order_with_respect_to):
  632. self.order_with_respect_to = order_with_respect_to
  633. super().__init__(name)
  634. def deconstruct(self):
  635. kwargs = {
  636. "name": self.name,
  637. "order_with_respect_to": self.order_with_respect_to,
  638. }
  639. return (self.__class__.__qualname__, [], kwargs)
  640. def state_forwards(self, app_label, state):
  641. state.alter_model_options(
  642. app_label,
  643. self.name_lower,
  644. {self.option_name: self.order_with_respect_to},
  645. )
  646. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  647. to_model = to_state.apps.get_model(app_label, self.name)
  648. if self.allow_migrate_model(schema_editor.connection.alias, to_model):
  649. from_model = from_state.apps.get_model(app_label, self.name)
  650. # Remove a field if we need to
  651. if (
  652. from_model._meta.order_with_respect_to
  653. and not to_model._meta.order_with_respect_to
  654. ):
  655. schema_editor.remove_field(
  656. from_model, from_model._meta.get_field("_order")
  657. )
  658. # Add a field if we need to (altering the column is untouched as
  659. # it's likely a rename)
  660. elif (
  661. to_model._meta.order_with_respect_to
  662. and not from_model._meta.order_with_respect_to
  663. ):
  664. field = to_model._meta.get_field("_order")
  665. if not field.has_default():
  666. field.default = 0
  667. schema_editor.add_field(
  668. from_model,
  669. field,
  670. )
  671. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  672. self.database_forwards(app_label, schema_editor, from_state, to_state)
  673. def references_field(self, model_name, name, app_label):
  674. return self.references_model(model_name, app_label) and (
  675. self.order_with_respect_to is None or name == self.order_with_respect_to
  676. )
  677. def describe(self):
  678. return "Set order_with_respect_to on %s to %s" % (
  679. self.name,
  680. self.order_with_respect_to,
  681. )
  682. @property
  683. def migration_name_fragment(self):
  684. return "alter_%s_order_with_respect_to" % self.name_lower
  685. class AlterModelOptions(ModelOptionOperation):
  686. """
  687. Set new model options that don't directly affect the database schema
  688. (like verbose_name, permissions, ordering). Python code in migrations
  689. may still need them.
  690. """
  691. # Model options we want to compare and preserve in an AlterModelOptions op
  692. ALTER_OPTION_KEYS = [
  693. "base_manager_name",
  694. "default_manager_name",
  695. "default_related_name",
  696. "get_latest_by",
  697. "managed",
  698. "ordering",
  699. "permissions",
  700. "default_permissions",
  701. "select_on_save",
  702. "verbose_name",
  703. "verbose_name_plural",
  704. ]
  705. def __init__(self, name, options):
  706. self.options = options
  707. super().__init__(name)
  708. def deconstruct(self):
  709. kwargs = {
  710. "name": self.name,
  711. "options": self.options,
  712. }
  713. return (self.__class__.__qualname__, [], kwargs)
  714. def state_forwards(self, app_label, state):
  715. state.alter_model_options(
  716. app_label,
  717. self.name_lower,
  718. self.options,
  719. self.ALTER_OPTION_KEYS,
  720. )
  721. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  722. pass
  723. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  724. pass
  725. def describe(self):
  726. return "Change Meta options on %s" % self.name
  727. @property
  728. def migration_name_fragment(self):
  729. return "alter_%s_options" % self.name_lower
  730. class AlterModelManagers(ModelOptionOperation):
  731. """Alter the model's managers."""
  732. serialization_expand_args = ["managers"]
  733. def __init__(self, name, managers):
  734. self.managers = managers
  735. super().__init__(name)
  736. def deconstruct(self):
  737. return (self.__class__.__qualname__, [self.name, self.managers], {})
  738. def state_forwards(self, app_label, state):
  739. state.alter_model_managers(app_label, self.name_lower, self.managers)
  740. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  741. pass
  742. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  743. pass
  744. def describe(self):
  745. return "Change managers on %s" % self.name
  746. @property
  747. def migration_name_fragment(self):
  748. return "alter_%s_managers" % self.name_lower
  749. class IndexOperation(Operation):
  750. option_name = "indexes"
  751. @cached_property
  752. def model_name_lower(self):
  753. return self.model_name.lower()
  754. class AddIndex(IndexOperation):
  755. """Add an index on a model."""
  756. def __init__(self, model_name, index):
  757. self.model_name = model_name
  758. if not index.name:
  759. raise ValueError(
  760. "Indexes passed to AddIndex operations require a name "
  761. "argument. %r doesn't have one." % index
  762. )
  763. self.index = index
  764. def state_forwards(self, app_label, state):
  765. state.add_index(app_label, self.model_name_lower, self.index)
  766. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  767. model = to_state.apps.get_model(app_label, self.model_name)
  768. if self.allow_migrate_model(schema_editor.connection.alias, model):
  769. schema_editor.add_index(model, self.index)
  770. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  771. model = from_state.apps.get_model(app_label, self.model_name)
  772. if self.allow_migrate_model(schema_editor.connection.alias, model):
  773. schema_editor.remove_index(model, self.index)
  774. def deconstruct(self):
  775. kwargs = {
  776. "model_name": self.model_name,
  777. "index": self.index,
  778. }
  779. return (
  780. self.__class__.__qualname__,
  781. [],
  782. kwargs,
  783. )
  784. def describe(self):
  785. if self.index.expressions:
  786. return "Create index %s on %s on model %s" % (
  787. self.index.name,
  788. ", ".join([str(expression) for expression in self.index.expressions]),
  789. self.model_name,
  790. )
  791. return "Create index %s on field(s) %s of model %s" % (
  792. self.index.name,
  793. ", ".join(self.index.fields),
  794. self.model_name,
  795. )
  796. @property
  797. def migration_name_fragment(self):
  798. return "%s_%s" % (self.model_name_lower, self.index.name.lower())
  799. def reduce(self, operation, app_label):
  800. if isinstance(operation, RemoveIndex) and self.index.name == operation.name:
  801. return []
  802. if isinstance(operation, RenameIndex) and self.index.name == operation.old_name:
  803. self.index.name = operation.new_name
  804. return [AddIndex(model_name=self.model_name, index=self.index)]
  805. return super().reduce(operation, app_label)
  806. class RemoveIndex(IndexOperation):
  807. """Remove an index from a model."""
  808. def __init__(self, model_name, name):
  809. self.model_name = model_name
  810. self.name = name
  811. def state_forwards(self, app_label, state):
  812. state.remove_index(app_label, self.model_name_lower, self.name)
  813. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  814. model = from_state.apps.get_model(app_label, self.model_name)
  815. if self.allow_migrate_model(schema_editor.connection.alias, model):
  816. from_model_state = from_state.models[app_label, self.model_name_lower]
  817. index = from_model_state.get_index_by_name(self.name)
  818. schema_editor.remove_index(model, index)
  819. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  820. model = to_state.apps.get_model(app_label, self.model_name)
  821. if self.allow_migrate_model(schema_editor.connection.alias, model):
  822. to_model_state = to_state.models[app_label, self.model_name_lower]
  823. index = to_model_state.get_index_by_name(self.name)
  824. schema_editor.add_index(model, index)
  825. def deconstruct(self):
  826. kwargs = {
  827. "model_name": self.model_name,
  828. "name": self.name,
  829. }
  830. return (
  831. self.__class__.__qualname__,
  832. [],
  833. kwargs,
  834. )
  835. def describe(self):
  836. return "Remove index %s from %s" % (self.name, self.model_name)
  837. @property
  838. def migration_name_fragment(self):
  839. return "remove_%s_%s" % (self.model_name_lower, self.name.lower())
  840. class RenameIndex(IndexOperation):
  841. """Rename an index."""
  842. def __init__(self, model_name, new_name, old_name=None, old_fields=None):
  843. if not old_name and not old_fields:
  844. raise ValueError(
  845. "RenameIndex requires one of old_name and old_fields arguments to be "
  846. "set."
  847. )
  848. if old_name and old_fields:
  849. raise ValueError(
  850. "RenameIndex.old_name and old_fields are mutually exclusive."
  851. )
  852. self.model_name = model_name
  853. self.new_name = new_name
  854. self.old_name = old_name
  855. self.old_fields = old_fields
  856. @cached_property
  857. def old_name_lower(self):
  858. return self.old_name.lower()
  859. @cached_property
  860. def new_name_lower(self):
  861. return self.new_name.lower()
  862. def deconstruct(self):
  863. kwargs = {
  864. "model_name": self.model_name,
  865. "new_name": self.new_name,
  866. }
  867. if self.old_name:
  868. kwargs["old_name"] = self.old_name
  869. if self.old_fields:
  870. kwargs["old_fields"] = self.old_fields
  871. return (self.__class__.__qualname__, [], kwargs)
  872. def state_forwards(self, app_label, state):
  873. if self.old_fields:
  874. state.add_index(
  875. app_label,
  876. self.model_name_lower,
  877. models.Index(fields=self.old_fields, name=self.new_name),
  878. )
  879. state.remove_model_options(
  880. app_label,
  881. self.model_name_lower,
  882. AlterIndexTogether.option_name,
  883. self.old_fields,
  884. )
  885. else:
  886. state.rename_index(
  887. app_label, self.model_name_lower, self.old_name, self.new_name
  888. )
  889. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  890. model = to_state.apps.get_model(app_label, self.model_name)
  891. if not self.allow_migrate_model(schema_editor.connection.alias, model):
  892. return
  893. if self.old_fields:
  894. from_model = from_state.apps.get_model(app_label, self.model_name)
  895. columns = [
  896. from_model._meta.get_field(field).column for field in self.old_fields
  897. ]
  898. matching_index_name = schema_editor._constraint_names(
  899. from_model, column_names=columns, index=True
  900. )
  901. if len(matching_index_name) != 1:
  902. raise ValueError(
  903. "Found wrong number (%s) of indexes for %s(%s)."
  904. % (
  905. len(matching_index_name),
  906. from_model._meta.db_table,
  907. ", ".join(columns),
  908. )
  909. )
  910. old_index = models.Index(
  911. fields=self.old_fields,
  912. name=matching_index_name[0],
  913. )
  914. else:
  915. from_model_state = from_state.models[app_label, self.model_name_lower]
  916. old_index = from_model_state.get_index_by_name(self.old_name)
  917. # Don't alter when the index name is not changed.
  918. if old_index.name == self.new_name:
  919. return
  920. to_model_state = to_state.models[app_label, self.model_name_lower]
  921. new_index = to_model_state.get_index_by_name(self.new_name)
  922. schema_editor.rename_index(model, old_index, new_index)
  923. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  924. if self.old_fields:
  925. # Backward operation with unnamed index is a no-op.
  926. return
  927. self.new_name_lower, self.old_name_lower = (
  928. self.old_name_lower,
  929. self.new_name_lower,
  930. )
  931. self.new_name, self.old_name = self.old_name, self.new_name
  932. self.database_forwards(app_label, schema_editor, from_state, to_state)
  933. self.new_name_lower, self.old_name_lower = (
  934. self.old_name_lower,
  935. self.new_name_lower,
  936. )
  937. self.new_name, self.old_name = self.old_name, self.new_name
  938. def describe(self):
  939. if self.old_name:
  940. return (
  941. f"Rename index {self.old_name} on {self.model_name} to {self.new_name}"
  942. )
  943. return (
  944. f"Rename unnamed index for {self.old_fields} on {self.model_name} to "
  945. f"{self.new_name}"
  946. )
  947. @property
  948. def migration_name_fragment(self):
  949. if self.old_name:
  950. return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower)
  951. return "rename_%s_%s_%s" % (
  952. self.model_name_lower,
  953. "_".join(self.old_fields),
  954. self.new_name_lower,
  955. )
  956. def reduce(self, operation, app_label):
  957. if (
  958. isinstance(operation, RenameIndex)
  959. and self.model_name_lower == operation.model_name_lower
  960. and operation.old_name
  961. and self.new_name_lower == operation.old_name_lower
  962. ):
  963. return [
  964. RenameIndex(
  965. self.model_name,
  966. new_name=operation.new_name,
  967. old_name=self.old_name,
  968. old_fields=self.old_fields,
  969. )
  970. ]
  971. return super().reduce(operation, app_label)
  972. class AddConstraint(IndexOperation):
  973. option_name = "constraints"
  974. def __init__(self, model_name, constraint):
  975. self.model_name = model_name
  976. self.constraint = constraint
  977. def state_forwards(self, app_label, state):
  978. state.add_constraint(app_label, self.model_name_lower, self.constraint)
  979. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  980. model = to_state.apps.get_model(app_label, self.model_name)
  981. if self.allow_migrate_model(schema_editor.connection.alias, model):
  982. schema_editor.add_constraint(model, self.constraint)
  983. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  984. model = to_state.apps.get_model(app_label, self.model_name)
  985. if self.allow_migrate_model(schema_editor.connection.alias, model):
  986. schema_editor.remove_constraint(model, self.constraint)
  987. def deconstruct(self):
  988. return (
  989. self.__class__.__name__,
  990. [],
  991. {
  992. "model_name": self.model_name,
  993. "constraint": self.constraint,
  994. },
  995. )
  996. def describe(self):
  997. return "Create constraint %s on model %s" % (
  998. self.constraint.name,
  999. self.model_name,
  1000. )
  1001. @property
  1002. def migration_name_fragment(self):
  1003. return "%s_%s" % (self.model_name_lower, self.constraint.name.lower())
  1004. def reduce(self, operation, app_label):
  1005. if (
  1006. isinstance(operation, RemoveConstraint)
  1007. and self.model_name_lower == operation.model_name_lower
  1008. and self.constraint.name == operation.name
  1009. ):
  1010. return []
  1011. return super().reduce(operation, app_label)
  1012. class RemoveConstraint(IndexOperation):
  1013. option_name = "constraints"
  1014. def __init__(self, model_name, name):
  1015. self.model_name = model_name
  1016. self.name = name
  1017. def state_forwards(self, app_label, state):
  1018. state.remove_constraint(app_label, self.model_name_lower, self.name)
  1019. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  1020. model = to_state.apps.get_model(app_label, self.model_name)
  1021. if self.allow_migrate_model(schema_editor.connection.alias, model):
  1022. from_model_state = from_state.models[app_label, self.model_name_lower]
  1023. constraint = from_model_state.get_constraint_by_name(self.name)
  1024. schema_editor.remove_constraint(model, constraint)
  1025. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  1026. model = to_state.apps.get_model(app_label, self.model_name)
  1027. if self.allow_migrate_model(schema_editor.connection.alias, model):
  1028. to_model_state = to_state.models[app_label, self.model_name_lower]
  1029. constraint = to_model_state.get_constraint_by_name(self.name)
  1030. schema_editor.add_constraint(model, constraint)
  1031. def deconstruct(self):
  1032. return (
  1033. self.__class__.__name__,
  1034. [],
  1035. {
  1036. "model_name": self.model_name,
  1037. "name": self.name,
  1038. },
  1039. )
  1040. def describe(self):
  1041. return "Remove constraint %s from model %s" % (self.name, self.model_name)
  1042. @property
  1043. def migration_name_fragment(self):
  1044. return "remove_%s_%s" % (self.model_name_lower, self.name.lower())