In my django project I have the following:
apps1/models.py: Post (model)
apps2/models.py: Blogs (model)
apps2/functions.py: get_blogs (method)
The apps1/models.py file imports the Blogs model from apps2/models.py.
The apps2/models.py file imports the get_blogs method from apps2/functions.py.
The apps2/functions.py file import the Post model from apps1/models.py.
I am getting the following error:
ImportError at /
cannot import name Post
Traceback
admin.autodiscover()
<in file apps1/models.py>
from apps2.models import Blogs
<in file apps2/models.py>
from apps2.functions import get_blogs
<in file apps2/functions.py>
from apps1.models import Post
I thought it might be that the admin.autodiscover is importing the Post model first and then through an import loop, it is trying to import it again. Although I tried changing it to:
from apps1.models import Post as OtherPost
but that didn’t help. Any idea why this is happening? Is it because there is a loop now?
If the only reason you import
Blogsinapps1.modelsis that you have a relationship field inPost, how about using a lazy relationship instead? As far as I understand, those were designed specifically to deal with import loops like the one you’re experiencing.It is quite easy, instead of
you use something like this: