[settings.py] How do I change the DB used when project is spun up in ci/cd (github actions)?

My apologies if this has been answered already. I am trying to figure out how to get Django to use sqlite3 when doing automated tests through github actions, but use mssql when run locally. The reason is because well… I can’t just spin up a mssql server instance in my github actions, or not that I am aware of. Perhaps there is a better solution that gets around this problem to begin with, and I’m all ears.

So far, I’ve tried something like this:

settings.py

if len(sys.argv) > 2 and sys.argv[2] == "sqlite3":
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

else:
    DATABASES = { 
        "default": {
            "ENGINE": "mssql",
            ...
        }
}

The problem with this approach is that I have to type python manage.py runserver sqlite3 to get django to connect to it, which I found out the hard way, interferes with a lot of other operations, such as migrate. Is there a best practice that tackles this kind of situation?

One way to do this would be to set the desired database settings as an environment variable, and test that environment variable in your settings.

For an example of another idea along these lines, see GitHub - jacobian/dj-database-url: Use Database URLs in your Django Application.

Thank you for your prompt response. Using environment variables as the trigger point should work nicely. I heard that this should be avoided in production, though. Would you happen to have suggestions for a prod environment?

For completeness, this is the solution I came up with for now. I hope this helps someone else out in the future.

manage.py

if os.getenv('DB') == "sqlite3":
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
else:
    DATABASES = { 
        "default": {
            "ENGINE": "mssql",
            ...
        }
}

.env (change sqlite3 to empty string or something else to use production)

DB="sqlite3"

I’m not sure where you might have heard that. Using environment variables is absolutely one of the most reliable means of managing differences between deployment environments.