简体   繁体   中英

Import app model with multiple Django apps error ModuleNotFoundError: No module named 'apps'

So I have a problem importing a model from a different app in same Django project.

My files are structured as follows:

/project
    /apps  
       __init__.py
       /app1
          __init__.py
          models.py
          ...
       /non_app_dir
          __init__.py
          work.py
       ...
   /core
       __init.py
       settings.py
       urls.py
       wsgi.py
       ...  
manage.py

In my settings.py, I have this:

INSTALLED_APPS = [
    ...
    'apps.app1',
    'apps.non_app_dir',
    ...
]

Ok, so in my work.py (from non_app_dir), I try to import a model from models.py (from app1) like below:

from apps.app1.models import MyModel

def testModel():
    
    test = MyModel.objects.all()
    print(test)

but i get the following error

ModuleNotFoundError: No module named 'apps'

Any solutions to this?

Create two seperate apps using following structure.

/project

   /app1
          __init__.py
          models.py
    
   /non_app_dir
          __init__.py
          work.py
  
   /core
       __init.py
       settings.py
       urls.py
       wsgi.py
       
    manage.py

Inside, core urls.py include urls,

    path('path1/', include('app1.urls'),
    path('path2/', include('non_app_dir.urls')

In your app1/apps.py be sure to add name = 'apps.app1' to the app config class. Like:

from django.apps import AppConfig

class App1Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.app1'
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM