Django - Warning "Accessing the database during app initialization is discouraged" in AppConfig.ready() after update
Recently, I’ve updated Django to the latest version, 5.1.2, and since then, every time I start the server, I get this warning:
RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported.
From what I’ve searched so far, my apps.py file is causing this due to the operation it’s executing on the database:
from django.apps import AppConfig
class TenantsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tenants'
def ready(self):
self.load_additional_databases()
def load_additional_databases(self):
from django.conf import settings
from .models import DatabaseConfig
for config in DatabaseConfig.objects.all():
if config.name not in settings.DATABASES:
db_settings = settings.DATABASES['default'].copy()
db_settings.update({
'ENGINE': config.engine,
'NAME': config.database_name,
'USER': config.user,
'PASSWORD': config.password,
'HOST': config.host,
'PORT': config.port,
})
settings.DATABASES[config.name] = db_settings
My settings.py has two main databases (default and tenants) hard-coded and the other configurations should be updated with data from the model DatabaseConfig when I start the server. The problem is that I need this exact behavior, but the solution I’ve found so far, is to use connection_created which makes this run for every database query. This is the implementation using the signal:
def db_config(**kwargs):
from django.conf import settings
from .models import DatabaseConfig
for config in DatabaseConfig.objects.all():
if config.name not in settings.DATABASES:
db_settings = settings.DATABASES['default'].copy()
db_settings.update({
'ENGINE': config.engine,
'NAME': config.database_name,
'USER': config.user,
'PASSWORD': config.password,
'HOST': config.host,
'PORT': config.port,
})
settings.DATABASES[config.name] = db_settings
class TenantsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tenants'
def ready(self):
connection_created.connect(db_config)
Is there another way to achieve the previous behavior in the ready method? Or is it really that bad to keep using it with the warning? For what I understand from the docs, this should be avoided, but is not necessarily bad. The docs mention the save() and delete() methods, but here I’m just updating the settings.py file. Any help would be appreciated.