Skip to content

Instantly share code, notes, and snippets.

@dorosch
Created May 17, 2020 14:38
Show Gist options
  • Save dorosch/086e199cb81f791f514f9f8ceacf8b95 to your computer and use it in GitHub Desktop.
Save dorosch/086e199cb81f791f514f9f8ceacf8b95 to your computer and use it in GitHub Desktop.
Dynamically create an additional list of databases for settings.py
from django import apps
from django import conf
from apps.database.models import Database
class DatabaseAppConfig(apps.AppConfig):
"""
You can only supplement the list of standard database settings
when loading the application, since during the first pass through
the settings.py file the application models are not loaded yet
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Dynamically create an additional list of databases
databases = {
db.distribution_center: {
'NAME': db.name,
'ENGINE': db.engine,
'USER': db.user or '',
'PASSWORD': db.password or '',
'HOST': db.host or '',
'PORT': db.port or '',
}
for db in Database.objects.all()
}
# Update settings to add additional databases
conf.settings.DATABASES.update(databases)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment