manager.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from typing import Optional
  2. from django.conf import settings
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.db import connections
  5. from django.db.models import Manager
  6. from psqlextra.query import PostgresQuerySet
  7. class PostgresManager(Manager.from_queryset(PostgresQuerySet)):
  8. """Adds support for PostgreSQL specifics."""
  9. use_in_migrations = True
  10. def __init__(self, *args, **kwargs):
  11. """Initializes a new instance of :see:PostgresManager."""
  12. super().__init__(*args, **kwargs)
  13. # make sure our back-end is set in at least one db and refuse to proceed
  14. has_psqlextra_backend = any(
  15. [
  16. db_settings
  17. for db_settings in settings.DATABASES.values()
  18. if "psqlextra" in db_settings["ENGINE"]
  19. ]
  20. )
  21. if not has_psqlextra_backend:
  22. raise ImproperlyConfigured(
  23. (
  24. "Could not locate the 'psqlextra.backend'. "
  25. "django-postgres-extra cannot function without "
  26. "the 'psqlextra.backend'. Set DATABASES.ENGINE."
  27. )
  28. )
  29. def truncate(
  30. self, cascade: bool = False, using: Optional[str] = None
  31. ) -> None:
  32. """Truncates this model/table using the TRUNCATE statement.
  33. This DELETES ALL ROWS. No signals will be fired.
  34. See: https://www.postgresql.org/docs/9.1/sql-truncate.html
  35. Arguments:
  36. cascade:
  37. Whether to delete dependent rows. If set to
  38. False, an error will be raised if there
  39. are rows in other tables referencing
  40. the rows you're trying to delete.
  41. """
  42. connection = connections[using or "default"]
  43. table_name = connection.ops.quote_name(self.model._meta.db_table)
  44. with connection.cursor() as cursor:
  45. sql = "TRUNCATE TABLE %s" % table_name
  46. if cascade:
  47. sql += " CASCADE"
  48. cursor.execute(sql)