create_view_model.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from django.db.migrations.operations.models import CreateModel
  2. from psqlextra.backend.migrations.state import PostgresViewModelState
  3. class PostgresCreateViewModel(CreateModel):
  4. """Creates the model as a native PostgreSQL 11.x view."""
  5. serialization_expand_args = [
  6. "fields",
  7. "options",
  8. "managers",
  9. "view_options",
  10. ]
  11. def __init__(
  12. self,
  13. name,
  14. fields,
  15. options=None,
  16. view_options={},
  17. bases=None,
  18. managers=None,
  19. ):
  20. super().__init__(name, fields, options, bases, managers)
  21. self.view_options = view_options or {}
  22. def state_forwards(self, app_label, state):
  23. state.add_model(
  24. PostgresViewModelState(
  25. app_label=app_label,
  26. name=self.name,
  27. fields=list(self.fields),
  28. options=dict(self.options),
  29. bases=tuple(self.bases),
  30. managers=list(self.managers),
  31. view_options=dict(self.view_options),
  32. )
  33. )
  34. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  35. """Apply this migration operation forwards."""
  36. model = to_state.apps.get_model(app_label, self.name)
  37. if self.allow_migrate_model(schema_editor.connection.alias, model):
  38. schema_editor.create_view_model(model)
  39. def database_backwards(
  40. self, app_label, schema_editor, from_state, to_state
  41. ):
  42. """Apply this migration operation backwards."""
  43. model = from_state.apps.get_model(app_label, self.name)
  44. if self.allow_migrate_model(schema_editor.connection.alias, model):
  45. schema_editor.delete_view_model(model)
  46. def deconstruct(self):
  47. name, args, kwargs = super().deconstruct()
  48. if self.view_options:
  49. kwargs["view_options"] = self.view_options
  50. return name, args, kwargs
  51. def describe(self):
  52. """Gets a human readable text describing this migration."""
  53. description = super().describe()
  54. description = description.replace("model", "view model")
  55. return description