Django: dynamic database file

The django.db.connections is a simple wrapper around DATABASES defined in your settings. The wrapper class is here: django.db.utils#L137-L227 from django.db import connections # Add connection information dynamically.. connections.databases[‘new-alias’] = { … } # Ensure the remaining default connection information is defined. # EDIT: this is actually performed for you in the wrapper class __getitem__ # … Read more

Simple Subquery with OuterRef

One of the problems with your example is that you cannot use queryset.count() as a subquery, because .count() tries to evaluate the queryset and return the count. So one may think that the right approach would be to use Count() instead. Maybe something like this: Post.objects.annotate( count=Count(Tag.objects.filter(post=OuterRef(‘pk’))) ) This won’t work for two reasons: The … Read more

How to log all sql queries in Django?

Merge the following snippet with the LOGGING field in your settings.py: LOGGING = { ‘version’: 1, ‘filters’: { ‘require_debug_true’: { ‘()’: ‘django.utils.log.RequireDebugTrue’, } }, ‘handlers’: { ‘console’: { ‘level’: ‘DEBUG’, ‘filters’: [‘require_debug_true’], ‘class’: ‘logging.StreamHandler’, } }, ‘loggers’: { ‘django.db.backends’: { ‘level’: ‘DEBUG’, ‘handlers’: [‘console’], } } } Tweaked from @acardenas89 answer

How to see the raw SQL queries Django is running?

See the docs FAQ: “How can I see the raw SQL queries Django is running?“ django.db.connection.queries contains a list of the SQL queries: from django.db import connection print(connection.queries) Querysets also have a query attribute containing the query to be executed: print(MyModel.objects.filter(name=”my name”).query) Note that the output of the query is not valid SQL, because: “Django … Read more

Django – how to specify a database for a model?

You can’t specify a database for a model, but you can define it in a custom DB router class. # app/models.py class SomeModel(models.Model): … # app/dbrouters.py from app.models import SomeModel … class MyDBRouter(object): def db_for_read(self, model, **hints): “”” reading SomeModel from otherdb “”” if model == SomeModel: return ‘otherdb’ return None def db_for_write(self, model, **hints): … Read more