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 :)
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.
You can try this.
import importlib
mymodels = importlib.import_module("app.models")
mymodels.YourModel
#query
mymodels.YourModel.objects.all()
Related
I created a models within my page but when I attempted to run the page I received an error response
celery_beat_1 | class ClassManager(models.Manager):
celery_beat_1 | NameError: name 'models' is not defined
I searched for fixes to this error online and most of the responses said to implement the
import from django.db import models
function. However, this is something I already have configured in my models page. Any idea on how to proceed forward?
You should import models from django in models.py.
from django.db import models
class MyModel(models.Model):
pass
You can check more information in django documentation itself:
https://docs.djangoproject.com/en/3.2/topics/db/models/#quick-example
You are importing the models in wrong way format, so you have to use -
from django.db import models
rather than using
import from django.db import models
If I do that :
from myapp import models
User.objects.first()
I got that error :
NameError : name 'User' is not defined
whereas if I do that
import myapp
myapp.models.User.objects.first()
it works
I don't understand at all why I have that problem
Thank you very much for your help !
Replace:
from myapp import models
with the following:
This way, you are telling Django which model classes to import rather than leaving Django guessing what to do with it.
It prevents you from loading unnecessary models which might not be used right away and could potentially increase load time.
from myapp.models import User
In your example, your have not imported class User actually. You have imported it's module called models
You can do one of these:
from myapp import models
models.User.objects.first()
Or:
from myapp.models import User
User.objects.first()
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.
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
models.py
class Tipo(models.Model):
code= models.TextField()
def thename(self):
from myhelp import Diz_Tipi
return Diz_tipi[self.code]
myhelp.py
def creatediz():
return dict_Tipi
Diz_Tipi=creatediz()
This works but I don't think from myhelp import Diz_Tipi should be in that place.
If I add at the start of models.py it return:
File
"/local/lib/python2.7/site-packages/django/apps/registry.py",
line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
there is any other way to make Diz_Tipi available from all the modules?
This sounds like a circular dependency issue.
Note that the error says "Models aren't loaded yet.".
So, are you trying to import one of your models in myhelp? If so, that would create a circular dependency problem, because models.py is importing from myhelp.py and myhelp.py is importing from models.py.
there is a strange issue in django I faced with this, I would add the following to the top of the file:
import django
django.setup()
this in turn should load your apps before attempting model access, also make sure that the app that contains the models file is in the installed apps file in settings
I've got a weird problem.
I am building a Flask app with SQLAlchemy. I have a file with models, namely, models.py. And I have a User model there.
If I open my "views.py" and insert a string
import models
and then use the User model like
u=models.User.query.filter_by(name='John',password='Doe').first()
everything works fine.
But if instead of "import models" i put
from models import User
Python crashes and says:
ImportError: cannot import name User
how can this be possible?
you most likely have a circular import; your, lets say 'app' module:
# app.py
import models
...
def doSomething():
models.User....
but your models module also imports app
import app
class User:
...
since models imports app, and app imports models, python has not finished importing models at the point app tries to import models.User; the User class has not been defined (yet). Either break the cyclic import (make sure models doesn't import anything that also imports models), or you'll just have to make do with models.User instead of the shorter User in app.
Instead of
from models import User
use
from models import *
In this case, you are importing the models into views.py therefore if you need a class from models, import it from views.py and the circular import problem will be resolved.