|
1 | | -# django-query-prefixer |
| 1 | +# django-query-prefixer |
| 2 | + |
| 3 | +The Django Query Prefixer allows you to prepend annotations to every query |
| 4 | +executed within your Django project. This can be useful for monitoring. By |
| 5 | +adding custom prefixes to queries, you can gain insights into their origin, |
| 6 | +and can track their performance in a more organized manner. |
| 7 | + |
| 8 | +## Installation |
| 9 | + |
| 10 | +You can install `django-query-prefixer` using pip: |
| 11 | + |
| 12 | +```shell |
| 13 | +pip install django-query-prefixer |
| 14 | +``` |
| 15 | + |
| 16 | +## Usage |
| 17 | + |
| 18 | +1. Change database engine in your `settings.py` to |
| 19 | +`django_query_prefixer.backends.<database backend>`. |
| 20 | + |
| 21 | +```python |
| 22 | +DATABASES = { |
| 23 | + "default": { |
| 24 | + "ENGINE": "django_query_prefixer.backends.postgresql", |
| 25 | + "HOST": "127.0.0.1", |
| 26 | + "NAME": "postgres", |
| 27 | + "PASSWORD": "postgres", |
| 28 | + "USER": "postgres", |
| 29 | + } |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +2. (Optional) Add `django_query_prefixer.middlewares.request_route` to the |
| 34 | +`MIDDLEWARE` list. This middleware adds `route` and `view_name` prefixes to |
| 35 | +SQL queries. |
| 36 | + |
| 37 | +```python |
| 38 | +MIDDLEWARE = [ |
| 39 | + "django_query_prefixer.middlewares.request_route", |
| 40 | + # ... |
| 41 | +] |
| 42 | +``` |
| 43 | + |
| 44 | +3. Now, whenever queries are executed in your Django project, the configured prefixes |
| 45 | +will be automatically added to those queries. For example, a query like this: |
| 46 | + |
| 47 | +```python |
| 48 | +User.objects.filter(username='bob') |
| 49 | +``` |
| 50 | + |
| 51 | +will be executed as: |
| 52 | + |
| 53 | +```sql |
| 54 | +/* view_name=example route=/example */ SELECT ... FROM "auth_user" WHERE ("auth_user"."username" = 'bob') |
| 55 | +``` |
| 56 | + |
| 57 | +You can add additional context to queries using the `sql_prefixes` _contextmanager_: |
| 58 | + |
| 59 | +```python |
| 60 | +from django_query_prefixer import sql_prefixes |
| 61 | + |
| 62 | +with sql_prefixes(user_id=request.user.id, foo="bar"): |
| 63 | + User.objects.filter(username='bob') |
| 64 | +```` |
| 65 | + |
| 66 | +```sql |
| 67 | +/* user_id=X foo=bar view_name=example route=/example */ SELECT ... FROM "auth_user" WHERE ("auth_user"."username" = 'bob') |
| 68 | +``` |
| 69 | + |
| 70 | +## Contributing |
| 71 | + |
| 72 | +Contributions to `django-query-prefixer` are welcome! If you find a bug, want to |
| 73 | +add a new feature, or improve the documentation, please open an issue or submit |
| 74 | +a pull request in the GitHub repository. |
0 commit comments