Avoiding Circular Imports In Django Models (config Class)
Solution 1:
You can postpone loading the models.py
by loading it in the getConfig(data)
function, as a result we no longer need models.py
at the time we load config.py
:
# config.py (no import in the head)classConfigData(Enum):
STARTING_MONEY = 1defgetConfig(data):
from .models import Configuration
ifnotisinstance(data, ConfigData):
raise TypeError(f"{data} is not a valid configuration type")
try:
config = Configuration.objects.get_or_create()
except Configuration.MultipleObjectsReturned:
# Cleans database in case multiple configurations exist.
Configuration.objects.exclude(Configuration.objects.first()).delete()
return getConfig(data)
if data is ConfigData.MAXIMUM_STAKE:
return config.max_stake
We thus do not load models.py
in the config.py
. We only check if it is loaded (and load it if not) when we actually execute the getConfig
function, which is later in the process.
Solution 2:
Willem Van Onsem's solution is a good one. I have a different approach which I have used for circular model dependencies using django's Applications registry. I post it here as an alternate solution, in part because I'd like feedback from more experienced python coders as to whether or not there are problems with this approach.
In a utility module, define the following method:
from django.apps import apps as django_apps
defmodel_by_name(app_name, model_name):
return django_apps.get_app_config(app_name).get_model(model_name)
Then in your getConfig, omit the import and replace the line
config = Configuration.objects.get_or_create()
with the following:
config_class = model_by_name(APP_NAME, 'Configuration')
config = config_class.objects.get_or_create()
Post a Comment for "Avoiding Circular Imports In Django Models (config Class)"