Plain is headed towards 1.0! Subscribe for development updates →

  1class Operation:
  2    """
  3    Base class for migration operations.
  4
  5    It's responsible for both mutating the in-memory model state
  6    (see db/migrations/state.py) to represent what it performs, as well
  7    as actually performing it against a live database.
  8
  9    Note that some operations won't modify memory state at all (e.g. data
 10    copying operations), and some will need their modifications to be
 11    optionally specified by the user (e.g. custom Python code snippets)
 12
 13    Due to the way this class deals with deconstruction, it should be
 14    considered immutable.
 15    """
 16
 17    # Can this migration be represented as SQL? (things like RunPython cannot)
 18    reduces_to_sql = True
 19
 20    # Should this operation be forced as atomic even on backends with no
 21    # DDL transaction support (i.e., does it have no DDL, like RunPython)
 22    atomic = False
 23
 24    # Should this operation be considered safe to elide and optimize across?
 25    elidable = False
 26
 27    serialization_expand_args = []
 28
 29    def __new__(cls, *args, **kwargs):
 30        # We capture the arguments to make returning them trivial
 31        self = object.__new__(cls)
 32        self._constructor_args = (args, kwargs)
 33        return self
 34
 35    def deconstruct(self):
 36        """
 37        Return a 3-tuple of class import path (or just name if it lives
 38        under plain.models.migrations), positional arguments, and keyword
 39        arguments.
 40        """
 41        return (
 42            self.__class__.__name__,
 43            self._constructor_args[0],
 44            self._constructor_args[1],
 45        )
 46
 47    def state_forwards(self, package_label, state):
 48        """
 49        Take the state from the previous migration, and mutate it
 50        so that it matches what this migration would perform.
 51        """
 52        raise NotImplementedError(
 53            "subclasses of Operation must provide a state_forwards() method"
 54        )
 55
 56    def database_forwards(self, package_label, schema_editor, from_state, to_state):
 57        """
 58        Perform the mutation on the database schema in the normal
 59        (forwards) direction.
 60        """
 61        raise NotImplementedError(
 62            "subclasses of Operation must provide a database_forwards() method"
 63        )
 64
 65    def describe(self):
 66        """
 67        Output a brief summary of what the action does.
 68        """
 69        return f"{self.__class__.__name__}: {self._constructor_args}"
 70
 71    @property
 72    def migration_name_fragment(self):
 73        """
 74        A filename part suitable for automatically naming a migration
 75        containing this operation, or None if not applicable.
 76        """
 77        return None
 78
 79    def references_model(self, name, package_label):
 80        """
 81        Return True if there is a chance this operation references the given
 82        model name (as a string), with an app label for accuracy.
 83
 84        Used for optimization. If in doubt, return True;
 85        returning a false positive will merely make the optimizer a little
 86        less efficient, while returning a false negative may result in an
 87        unusable optimized migration.
 88        """
 89        return True
 90
 91    def references_field(self, model_name, name, package_label):
 92        """
 93        Return True if there is a chance this operation references the given
 94        field name, with an app label for accuracy.
 95
 96        Used for optimization. If in doubt, return True.
 97        """
 98        return self.references_model(model_name, package_label)
 99
100    def allow_migrate_model(self, connection, model):
101        """Return whether or not a model may be migrated."""
102        if not model._meta.can_migrate(connection):
103            return False
104
105        return True
106
107    def reduce(self, operation, package_label):
108        """
109        Return either a list of operations the actual operation should be
110        replaced with or a boolean that indicates whether or not the specified
111        operation can be optimized across.
112        """
113        if self.elidable:
114            return [operation]
115        elif operation.elidable:
116            return [self]
117        return False
118
119    def __repr__(self):
120        return "<{} {}{}>".format(
121            self.__class__.__name__,
122            ", ".join(map(repr, self._constructor_args[0])),
123            ",".join(" {}={!r}".format(*x) for x in self._constructor_args[1].items()),
124        )