@@ -32,9 +32,43 @@ def allow_migrate(self, *args, **kwargs):
32
32
33
33
class in_database :
34
34
"""
35
- A context manager and decorator for setting a specific database for the duration of a block of code.
35
+ A decorator and context manager to do queries on a given database.
36
+ :type database: str or dict
37
+ :param database: The database to run queries on. A string
38
+ will route through the matching database in
39
+ ``django.conf.settings.DATABASES``. A dictionary will set up a
40
+ connection with the given configuration and route queries to it.
41
+ :type read: bool, optional
42
+ :param read: Controls whether database reads will route through
43
+ the provided database. If ``False``, reads will route through
44
+ the ``'default'`` database. Defaults to ``True``.
45
+ :type write: bool, optional
46
+ :param write: Controls whether database writes will route to
47
+ the provided database. If ``False``, writes will route to
48
+ the ``'default'`` database. Defaults to ``False``.
49
+ When used as eithe a decorator or a context manager, `in_database`
50
+ requires a single argument, which is the name of the database to
51
+ route queries to, or a configuration dictionary for a database to
52
+ route to.
53
+ Usage as a context manager:
54
+ .. code-block:: python
55
+ from my_django_app.utils import tricky_query
56
+ with in_database('Database_A'):
57
+ results = tricky_query()
58
+ Usage as a decorator:
59
+ .. code-block:: python
60
+ from my_django_app.models import Account
61
+ @in_database('Database_B')
62
+ def lowest_id_account():
63
+ Account.objects.order_by('-id')[0]
64
+ Used with a configuration dictionary:
65
+ .. code-block:: python
66
+ db_config = {'ENGINE': 'django.db.backends.sqlite3',
67
+ 'NAME': 'path/to/mydatabase.db'}
68
+ with in_database(db_config):
69
+ # Run queries
36
70
"""
37
- def __init__ (self , database , read = True , write = False ):
71
+ def __init__ (self , database : str | dict , read = True , write = False ):
38
72
self .read = read
39
73
self .write = write
40
74
self .database = database
0 commit comments