Django Model Import Error When trying to Import in Another App's Model

Viewed 309

I'm working on a Django based project right now. I 'm getting an error something called AppRegistryNotReady when I'm trying to import a model into another app's model with django get_model() method.. Now the interesting this is, I can import the models from another app in the view files with the same get_model() method.

In views file:

from django.apps import apps
Course = apps.get_model('course', 'Course')
Order = apps.get_model('course', 'Order')

*Now everything is working parfectly.

In models file:

from django.apps import apps
Course = apps.get_model('course', 'Course')
Order = apps.get_model('course', 'Order')

*Now it is getting the following error:

File "/home/mohul/.local/share/virtualenvs/django-backend-and-view-1OsDTUBe/lib/python3.9/site-packages/django/apps/registry.py", line 141, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
2 Answers

This is from Django Docs.

You must define or import all models in your application’s models.py or models/__init__.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.

Once this stage completes, APIs that operate on models such as get_model() become usable.

https://docs.djangoproject.com/en/3.2/ref/applications/#how-applications-are-loaded

Finally I got the solution from my own. Many peoples get into this problem I saw around me.

Here how I solved the problem:

project-name/
...project-name/
...apps1/
.....models.py
...apps2/
.....models.py
...manage.py

Just the basic django project structure.

Now to import the models of apps1 into apps2: In apps2/models.py:

from apps1 import models as apps1Model

# Now accessing the models

apps1Model.Model1
apps1Model.Model2
Related