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

7👍

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.

👤f4lco

Leave a comment