Debian Codegraph @

django/db/migrations/operations/models.py

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