fields.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. from django.db.migrations.utils import field_references
  2. from django.db.models import NOT_PROVIDED
  3. from django.utils.functional import cached_property
  4. from .base import Operation, OperationCategory
  5. class FieldOperation(Operation):
  6. def __init__(self, model_name, name, field=None):
  7. self.model_name = model_name
  8. self.name = name
  9. self.field = field
  10. @cached_property
  11. def model_name_lower(self):
  12. return self.model_name.lower()
  13. @cached_property
  14. def name_lower(self):
  15. return self.name.lower()
  16. def is_same_model_operation(self, operation):
  17. return self.model_name_lower == operation.model_name_lower
  18. def is_same_field_operation(self, operation):
  19. return (
  20. self.is_same_model_operation(operation)
  21. and self.name_lower == operation.name_lower
  22. )
  23. def references_model(self, name, app_label):
  24. name_lower = name.lower()
  25. if name_lower == self.model_name_lower:
  26. return True
  27. if self.field:
  28. return bool(
  29. field_references(
  30. (app_label, self.model_name_lower),
  31. self.field,
  32. (app_label, name_lower),
  33. )
  34. )
  35. return False
  36. def references_field(self, model_name, name, app_label):
  37. model_name_lower = model_name.lower()
  38. # Check if this operation locally references the field.
  39. if model_name_lower == self.model_name_lower:
  40. if name == self.name:
  41. return True
  42. elif (
  43. self.field
  44. and hasattr(self.field, "from_fields")
  45. and name in self.field.from_fields
  46. ):
  47. return True
  48. # Check if this operation remotely references the field.
  49. if self.field is None:
  50. return False
  51. return bool(
  52. field_references(
  53. (app_label, self.model_name_lower),
  54. self.field,
  55. (app_label, model_name_lower),
  56. name,
  57. )
  58. )
  59. def reduce(self, operation, app_label):
  60. return super().reduce(operation, app_label) or not operation.references_field(
  61. self.model_name, self.name, app_label
  62. )
  63. class AddField(FieldOperation):
  64. """Add a field to a model."""
  65. category = OperationCategory.ADDITION
  66. def __init__(self, model_name, name, field, preserve_default=True):
  67. self.preserve_default = preserve_default
  68. super().__init__(model_name, name, field)
  69. def deconstruct(self):
  70. kwargs = {
  71. "model_name": self.model_name,
  72. "name": self.name,
  73. "field": self.field,
  74. }
  75. if self.preserve_default is not True:
  76. kwargs["preserve_default"] = self.preserve_default
  77. return (self.__class__.__name__, [], kwargs)
  78. def state_forwards(self, app_label, state):
  79. state.add_field(
  80. app_label,
  81. self.model_name_lower,
  82. self.name,
  83. self.field,
  84. self.preserve_default,
  85. )
  86. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  87. to_model = to_state.apps.get_model(app_label, self.model_name)
  88. if self.allow_migrate_model(schema_editor.connection.alias, to_model):
  89. from_model = from_state.apps.get_model(app_label, self.model_name)
  90. field = to_model._meta.get_field(self.name)
  91. if not self.preserve_default:
  92. field.default = self.field.default
  93. schema_editor.add_field(
  94. from_model,
  95. field,
  96. )
  97. if not self.preserve_default:
  98. field.default = NOT_PROVIDED
  99. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  100. from_model = from_state.apps.get_model(app_label, self.model_name)
  101. if self.allow_migrate_model(schema_editor.connection.alias, from_model):
  102. schema_editor.remove_field(
  103. from_model, from_model._meta.get_field(self.name)
  104. )
  105. def describe(self):
  106. return "Add field %s to %s" % (self.name, self.model_name)
  107. @property
  108. def migration_name_fragment(self):
  109. return "%s_%s" % (self.model_name_lower, self.name_lower)
  110. def reduce(self, operation, app_label):
  111. if isinstance(operation, FieldOperation) and self.is_same_field_operation(
  112. operation
  113. ):
  114. if isinstance(operation, AlterField):
  115. return [
  116. AddField(
  117. model_name=self.model_name,
  118. name=operation.name,
  119. field=operation.field,
  120. ),
  121. ]
  122. elif isinstance(operation, RemoveField):
  123. return []
  124. elif isinstance(operation, RenameField):
  125. return [
  126. AddField(
  127. model_name=self.model_name,
  128. name=operation.new_name,
  129. field=self.field,
  130. ),
  131. ]
  132. return super().reduce(operation, app_label)
  133. class RemoveField(FieldOperation):
  134. """Remove a field from a model."""
  135. category = OperationCategory.REMOVAL
  136. def deconstruct(self):
  137. kwargs = {
  138. "model_name": self.model_name,
  139. "name": self.name,
  140. }
  141. return (self.__class__.__name__, [], kwargs)
  142. def state_forwards(self, app_label, state):
  143. state.remove_field(app_label, self.model_name_lower, self.name)
  144. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  145. from_model = from_state.apps.get_model(app_label, self.model_name)
  146. if self.allow_migrate_model(schema_editor.connection.alias, from_model):
  147. schema_editor.remove_field(
  148. from_model, from_model._meta.get_field(self.name)
  149. )
  150. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  151. to_model = to_state.apps.get_model(app_label, self.model_name)
  152. if self.allow_migrate_model(schema_editor.connection.alias, to_model):
  153. from_model = from_state.apps.get_model(app_label, self.model_name)
  154. schema_editor.add_field(from_model, to_model._meta.get_field(self.name))
  155. def describe(self):
  156. return "Remove field %s from %s" % (self.name, self.model_name)
  157. @property
  158. def migration_name_fragment(self):
  159. return "remove_%s_%s" % (self.model_name_lower, self.name_lower)
  160. def reduce(self, operation, app_label):
  161. from .models import DeleteModel
  162. if (
  163. isinstance(operation, DeleteModel)
  164. and operation.name_lower == self.model_name_lower
  165. ):
  166. return [operation]
  167. return super().reduce(operation, app_label)
  168. class AlterField(FieldOperation):
  169. """
  170. Alter a field's database column (e.g. null, max_length) to the provided
  171. new field.
  172. """
  173. category = OperationCategory.ALTERATION
  174. def __init__(self, model_name, name, field, preserve_default=True):
  175. self.preserve_default = preserve_default
  176. super().__init__(model_name, name, field)
  177. def deconstruct(self):
  178. kwargs = {
  179. "model_name": self.model_name,
  180. "name": self.name,
  181. "field": self.field,
  182. }
  183. if self.preserve_default is not True:
  184. kwargs["preserve_default"] = self.preserve_default
  185. return (self.__class__.__name__, [], kwargs)
  186. def state_forwards(self, app_label, state):
  187. state.alter_field(
  188. app_label,
  189. self.model_name_lower,
  190. self.name,
  191. self.field,
  192. self.preserve_default,
  193. )
  194. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  195. to_model = to_state.apps.get_model(app_label, self.model_name)
  196. if self.allow_migrate_model(schema_editor.connection.alias, to_model):
  197. from_model = from_state.apps.get_model(app_label, self.model_name)
  198. from_field = from_model._meta.get_field(self.name)
  199. to_field = to_model._meta.get_field(self.name)
  200. if not self.preserve_default:
  201. to_field.default = self.field.default
  202. schema_editor.alter_field(from_model, from_field, to_field)
  203. if not self.preserve_default:
  204. to_field.default = NOT_PROVIDED
  205. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  206. self.database_forwards(app_label, schema_editor, from_state, to_state)
  207. def describe(self):
  208. return "Alter field %s on %s" % (self.name, self.model_name)
  209. @property
  210. def migration_name_fragment(self):
  211. return "alter_%s_%s" % (self.model_name_lower, self.name_lower)
  212. def reduce(self, operation, app_label):
  213. if isinstance(
  214. operation, (AlterField, RemoveField)
  215. ) and self.is_same_field_operation(operation):
  216. return [operation]
  217. elif (
  218. isinstance(operation, RenameField)
  219. and self.is_same_field_operation(operation)
  220. and self.field.db_column is None
  221. ):
  222. return [
  223. operation,
  224. AlterField(
  225. model_name=self.model_name,
  226. name=operation.new_name,
  227. field=self.field,
  228. ),
  229. ]
  230. return super().reduce(operation, app_label)
  231. class RenameField(FieldOperation):
  232. """Rename a field on the model. Might affect db_column too."""
  233. category = OperationCategory.ALTERATION
  234. def __init__(self, model_name, old_name, new_name):
  235. self.old_name = old_name
  236. self.new_name = new_name
  237. super().__init__(model_name, old_name)
  238. @cached_property
  239. def old_name_lower(self):
  240. return self.old_name.lower()
  241. @cached_property
  242. def new_name_lower(self):
  243. return self.new_name.lower()
  244. def deconstruct(self):
  245. kwargs = {
  246. "model_name": self.model_name,
  247. "old_name": self.old_name,
  248. "new_name": self.new_name,
  249. }
  250. return (self.__class__.__name__, [], kwargs)
  251. def state_forwards(self, app_label, state):
  252. state.rename_field(
  253. app_label, self.model_name_lower, self.old_name, self.new_name
  254. )
  255. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  256. to_model = to_state.apps.get_model(app_label, self.model_name)
  257. if self.allow_migrate_model(schema_editor.connection.alias, to_model):
  258. from_model = from_state.apps.get_model(app_label, self.model_name)
  259. schema_editor.alter_field(
  260. from_model,
  261. from_model._meta.get_field(self.old_name),
  262. to_model._meta.get_field(self.new_name),
  263. )
  264. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  265. to_model = to_state.apps.get_model(app_label, self.model_name)
  266. if self.allow_migrate_model(schema_editor.connection.alias, to_model):
  267. from_model = from_state.apps.get_model(app_label, self.model_name)
  268. schema_editor.alter_field(
  269. from_model,
  270. from_model._meta.get_field(self.new_name),
  271. to_model._meta.get_field(self.old_name),
  272. )
  273. def describe(self):
  274. return "Rename field %s on %s to %s" % (
  275. self.old_name,
  276. self.model_name,
  277. self.new_name,
  278. )
  279. @property
  280. def migration_name_fragment(self):
  281. return "rename_%s_%s_%s" % (
  282. self.old_name_lower,
  283. self.model_name_lower,
  284. self.new_name_lower,
  285. )
  286. def references_field(self, model_name, name, app_label):
  287. return self.references_model(model_name, app_label) and (
  288. name.lower() == self.old_name_lower or name.lower() == self.new_name_lower
  289. )
  290. def reduce(self, operation, app_label):
  291. if (
  292. isinstance(operation, RenameField)
  293. and self.is_same_model_operation(operation)
  294. and self.new_name_lower == operation.old_name_lower
  295. ):
  296. return [
  297. RenameField(
  298. self.model_name,
  299. self.old_name,
  300. operation.new_name,
  301. ),
  302. ]
  303. # Skip `FieldOperation.reduce` as we want to run `references_field`
  304. # against self.old_name and self.new_name.
  305. return super(FieldOperation, self).reduce(operation, app_label) or not (
  306. operation.references_field(self.model_name, self.old_name, app_label)
  307. or operation.references_field(self.model_name, self.new_name, app_label)
  308. )