1👍
✅
The migrate
management command will detect if this is a new (i.e. forward) or previous (i.e. backward) migration, and call either the database_forwards
or database_backwards
method depending on the direction of the migration. The Operation
subclass doesn’t need to know the direction on init:
class AddField(FieldOperation):
...
def database_forwards(self, app_label, schema_editor, from_state, to_state):
to_model = to_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, to_model):
from_model = from_state.apps.get_model(app_label, self.model_name)
field = to_model._meta.get_field(self.name)
if not self.preserve_default:
field.default = self.field.default
schema_editor.add_field(
from_model,
field,
)
if not self.preserve_default:
field.default = NOT_PROVIDED
def database_backwards(self, app_label, schema_editor, from_state, to_state):
from_model = from_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, from_model):
schema_editor.remove_field(
from_model, from_model._meta.get_field(self.name)
)
This is partly explained in the documentation, specifically in reversing migrations and writing your own migration operations sections.
Source:stackexchange.com