pgrefreshmv.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from django.apps import apps
  2. from django.core.management.base import BaseCommand
  3. from django.db.utils import NotSupportedError, OperationalError
  4. from psqlextra.models import PostgresMaterializedViewModel
  5. class Command(BaseCommand):
  6. """Refreshes a :see:PostgresMaterializedViewModel."""
  7. help = "Refreshes the specified materialized view."
  8. def add_arguments(self, parser):
  9. parser.add_argument(
  10. "app_label",
  11. type=str,
  12. help="Label of the app the materialized view model is in.",
  13. )
  14. parser.add_argument(
  15. "model_name",
  16. type=str,
  17. help="Name of the materialized view model to refresh.",
  18. )
  19. parser.add_argument(
  20. "--concurrently",
  21. "-c",
  22. action="store_true",
  23. help="Whether to refresh the materialized view model concurrently.",
  24. required=False,
  25. default=False,
  26. )
  27. def handle(self, *app_labels, **options):
  28. app_label = options.get("app_label")
  29. model_name = options.get("model_name")
  30. concurrently = options.get("concurrently")
  31. model = apps.get_model(app_label, model_name)
  32. if not model:
  33. raise OperationalError(f"Cannot find a model named '{model_name}'")
  34. if not issubclass(model, PostgresMaterializedViewModel):
  35. raise NotSupportedError(
  36. f"Model {model.__name__} is not a `PostgresMaterializedViewModel`"
  37. )
  38. model.refresh(concurrently=concurrently)