How to access django models from a python file located in one level down
project_name/
├── manage.py
├── project_name/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── my_scripts/
└── script1.py
import os
import sys
# Add the parent directory to the Python path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Set DJANGO_SETTINGS_MODULE to the correct relative path
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
# Now you can import and use Django modules
import django
django.setup()
# Import Django models
from project_name.app1.models import MyModel
# Example usage
instances = MyModel.objects.all()
最近のコメント