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

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