我正在尝试在 Django 中执行一个不能完全正确导入模块的管理命令。
我的项目结构如下:
myproject/
|-- appname/
| |-- __init__.py
| |-- management/
| | |-- commands/
| | | |-- __init__.py
| | | |-- somefile.py
| | |--__init__.py
| |-- migrations/
| |-- admin.py
| |-- apps.py
| |-- views.py
| |-- models.py
| |-- urls.py
|-- myproject/
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
|-- manage.py
文件myapp/apps.py
:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
文件myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'
文件myapp/management/commands/somefile.py
from django.core.management import BaseCommand
from django.utils.datetime_safe import datetime
from myproject.myapp.models import Car
class Command(BaseCommand):
help = "Create initial data"
def handle(self, *args, **options):
cars = Car.objects.all()
print(cars)
self.stdout.write('Command successfully executed!')
错误:
Traceback (most recent call last):
File "myapp/management/commands/somefile.py", line 4, in <module>
from myproject.myapp.models import Car ModuleNotFoundError: No module named 'myproject'
如何配置应用程序以使管理命令地址正确的目录?