I need to run some custom database queries in my Django app that work with both SQLite and PostgreSQL. The problem is that these two databases use different SQL syntax for what I’m trying to do.
Right now I have no way to tell which database my Django app is actually connected to. I want to write conditional code that checks the database type first, then executes the correct query syntax.
For example, if it’s SQLite I’ll run one version of the query, but if it’s PostgreSQL I’ll run a different version. Is there a built-in Django method or setting I can check to determine the current database backend being used?
Interesting approaches! Quick question though - what about multiple database setups? If you’re using DATABASE_ROUTERS
or separate read/write databases, does connection.vendor
always return the right one? Or do you need to specify which connection you’re checking?
You can check which database Django is using by importing connection
from django.db
and looking at connection.vendor
. This gives you a string like ‘sqlite’, ‘postgresql’, or ‘mysql’. Works across different Django versions and it’s perfect for running conditional queries. I’ve used this approach in apps that needed multi-database support - handles different backend quirks really well.
i usually look at settings.DATABASES['default']['ENGINE']
too. it shows stuff like ‘django.db.backends.sqlite3’ or ‘django.db.backends.postgresql’. it’s a bit more detailed than just using connection.vendor but really helps for debugging.