Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Django use two different databases based on debug flag

I want to use the simple SQLite database on my local environment and use a Postgresql database in production. How can I configure the settings file to know which database to use based on the value of DEBUG?

like image 833
SAMUEL Tuyizere Avatar asked Nov 15 '25 04:11

SAMUEL Tuyizere


1 Answers

There are several options available:

  1. Below is a very cheap solution. Django always selects the database called 'default'. You can assign it conditionally in settings.py:

    DATABASES = {
        'dev': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        },
        'production': {
            'ENGINE': 'django.db.backends.postgresql',
            # ...
        },
    }
    
    DATABASES['default'] = DATABASES['dev' if DEBUG else 'production']
    
  2. You can implement an alternate settings module called settings_dev.py. Configure database there and use the environment variable DJANGO_SETTINGS_MODULE to point to yourapp.settings_dev.

  3. Implementing a custom database router. This is almost certainly overkill for many use-cases. See the Django documentation on multiple database support.

like image 63
f4lco Avatar answered Nov 17 '25 18:11

f4lco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!