mirror of
https://github.com/django/django.git
synced 2025-10-29 00:26:07 +00:00
Start adding operations that work and tests for them
This commit is contained in:
52
django/db/migrations/operations/fields.py
Normal file
52
django/db/migrations/operations/fields.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from .base import Operation
|
||||
|
||||
|
||||
class AddField(Operation):
|
||||
"""
|
||||
Adds a field to a model.
|
||||
"""
|
||||
|
||||
def __init__(self, model_name, name, instance):
|
||||
self.model_name = model_name
|
||||
self.name = name
|
||||
self.instance = instance
|
||||
|
||||
def state_forwards(self, app_label, state):
|
||||
state.models[app_label, self.model_name.lower()].fields.append((self.name, self.instance))
|
||||
|
||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||
app_cache = to_state.render()
|
||||
model = app_cache.get_model(app_label, self.name)
|
||||
schema_editor.add_field(model, model._meta.get_field_by_name(self.name))
|
||||
|
||||
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
||||
app_cache = from_state.render()
|
||||
model = app_cache.get_model(app_label, self.name)
|
||||
schema_editor.remove_field(model, model._meta.get_field_by_name(self.name))
|
||||
|
||||
|
||||
class RemoveField(Operation):
|
||||
"""
|
||||
Removes a field from a model.
|
||||
"""
|
||||
|
||||
def __init__(self, model_name, name):
|
||||
self.model_name = model_name
|
||||
self.name = name
|
||||
|
||||
def state_forwards(self, app_label, state):
|
||||
new_fields = []
|
||||
for name, instance in state.models[app_label, self.model_name.lower()].fields:
|
||||
if name != self.name:
|
||||
new_fields.append((name, instance))
|
||||
state.models[app_label, self.model_name.lower()].fields = new_fields
|
||||
|
||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||
app_cache = from_state.render()
|
||||
model = app_cache.get_model(app_label, self.name)
|
||||
schema_editor.remove_field(model, model._meta.get_field_by_name(self.name))
|
||||
|
||||
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
||||
app_cache = to_state.render()
|
||||
model = app_cache.get_model(app_label, self.name)
|
||||
schema_editor.add_field(model, model._meta.get_field_by_name(self.name))
|
||||
Reference in New Issue
Block a user