pythondjangodjango-models

Importing model classes from other apps in Django with cicular import Problem


Hi i Need to import a model into another app models that will raise the cicular import Error so i use the django.app like this :

from django.apps import apps

Order = apps.get_model(app_label="orders", model_name='Order')

its raise AppRegistryNotReady Error :

  File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\commands\runserver.py", line 126, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 116, in populate
    app_config.import_models()
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\config.py", line 269, in import_models
    self.models_module = import_module(models_module_name)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Pourya\Desktop\fapo\shop\models.py", line 17, in <module>
    Order = apps.get_model(app_label="orders", model_name='Order')
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 201, in get_model
    self.check_models_ready()
  File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 143, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

how can i fix this please help i have a live app :(


Solution

  • You don't need circular imports. Usually if you need to import a model, then that is either (1) to do something with the model in a function; or (2) to make a ForeignKey, ManyToManyField or another relation refer to that model.

    For the first case, you can import the model in the function where you calculate something, so instead of:

    from my_app.models import MyModel
    
    
    def my_function():
        # …

    rewrite this to:

    def my_function():
        from my_app.models import MyModel
    
        # …

    If you need to let a relation refer to it, you can use a string literal, so instead of:

    from my_app.models import MyModel
    
    
    class MyOtherModel(models.Model):
        my_foreignkey = models.ForeignKey(MyModel, on_delete=models.CASCADE)

    use:

    class MyOtherModel(models.Model):
        my_foreignkey = models.ForeignKey('my_app.MyModel', on_delete=models.CASCADE)