apps.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. from django.apps import AppConfig
  2. from django.db import connections
  3. class BaseAppConfig(AppConfig):
  4. name = "apps.query_performing_app"
  5. database = "default"
  6. def __init__(self, *args, **kwargs):
  7. super().__init__(*args, **kwargs)
  8. self.query_results = []
  9. def ready(self):
  10. self.query_results = []
  11. self._perform_query()
  12. def _perform_query(self):
  13. raise NotImplementedError
  14. class ModelQueryAppConfig(BaseAppConfig):
  15. def _perform_query(self):
  16. from ..models import TotallyNormal
  17. queryset = TotallyNormal.objects.using(self.database)
  18. queryset.update_or_create(name="new name")
  19. self.query_results = list(queryset.values_list("name"))
  20. class QueryDefaultDatabaseModelAppConfig(ModelQueryAppConfig):
  21. database = "default"
  22. class QueryOtherDatabaseModelAppConfig(ModelQueryAppConfig):
  23. database = "other"
  24. class CursorQueryAppConfig(BaseAppConfig):
  25. def _perform_query(self):
  26. connection = connections[self.database]
  27. with connection.cursor() as cursor:
  28. cursor.execute("SELECT 42" + connection.features.bare_select_suffix)
  29. self.query_results = cursor.fetchall()
  30. class QueryDefaultDatabaseCursorAppConfig(CursorQueryAppConfig):
  31. database = "default"
  32. class QueryOtherDatabaseCursorAppConfig(CursorQueryAppConfig):
  33. database = "other"
  34. class CursorQueryManyAppConfig(BaseAppConfig):
  35. def _perform_query(self):
  36. from ..models import TotallyNormal
  37. connection = connections[self.database]
  38. table_meta = TotallyNormal._meta
  39. with connection.cursor() as cursor:
  40. cursor.executemany(
  41. "INSERT INTO %s (%s) VALUES(%%s)"
  42. % (
  43. connection.introspection.identifier_converter(table_meta.db_table),
  44. connection.ops.quote_name(table_meta.get_field("name").column),
  45. ),
  46. [("test name 1",), ("test name 2",)],
  47. )
  48. self.query_results = []
  49. class QueryDefaultDatabaseCursorManyAppConfig(CursorQueryManyAppConfig):
  50. database = "default"
  51. class QueryOtherDatabaseCursorManyAppConfig(CursorQueryManyAppConfig):
  52. database = "other"
  53. class StoredProcedureQueryAppConfig(BaseAppConfig):
  54. def _perform_query(self):
  55. with connections[self.database].cursor() as cursor:
  56. cursor.callproc("test_procedure")
  57. self.query_results = []
  58. class QueryDefaultDatabaseStoredProcedureAppConfig(StoredProcedureQueryAppConfig):
  59. database = "default"
  60. class QueryOtherDatabaseStoredProcedureAppConfig(StoredProcedureQueryAppConfig):
  61. database = "other"