Reputation: 424
On circular import of Django Is their any way i can grab a model object with myModel = apps.get_model('app_name', 'model_name')
inside models.py file ?
I know i can use models.ForeignKey('app.model',....)
But in my case i am making a query in the models.py for custom function. So that i need to grab the model object. Also can't import it in normal way as already imported this file class in the other file. So must be a circular import.
This code myModel = apps.get_model('app_name', 'model_name')
works fine on views.py but in models.py doesn't. Since according to django the all models.py get called after settings.py and after that views and others. so while trying to use get_model
inside models.py getting this error
File "/home/mypc/.virtualenvs/VSkillza/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Thanks in advance :)
Upvotes: 1
Views: 4483
Reputation: 308779
You can break the circular import by moving the import inside the custom function. That way, the model is loaded when the function runs, not when the module is loaded.
def my_function():
from myapp.models import MyModel
The circular import suggests that your code is structured incorrectly, but we can't give you any suggestions since you haven't shown it.
Upvotes: 6
Reputation: 551
You can try this.
import importlib
mymodels = importlib.import_module("app.models")
mymodels.YourModel
#query
mymodels.YourModel.objects.all()
Upvotes: 2