Django has a great ORM, so there are times where you want to work with a Django project’s model or just model your data and use the ORM. You can use your models and its ORM in external Python scripts easily.
Since Django 1.4 the syntax to import you models in external scripts has changed. The setup_environ
method has been deprecated for a while and it no longer exists in current versions of Django.
Assuming your script is one directory outside the main Django project directory structure.
my_directory/
|
|---> my_django_project/ <--- Django project files
|---> my_script.py
Code language: HTML, XML (xml)
I use this for Django integration in my_script.py
:
import os
import sys
sys.path.append(
os.path.join(os.path.dirname(__file__), 'my_django_project')
)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_django_project.settings")
from django.conf import settings
from my_app.models import MyModel
Code language: JavaScript (javascript)
It’s very important to set the DJANGO_SETTINGS_MODULE
environment variable for the integration to work.
5 replies on “How to use Django models in external Python scripts”
Just want to say thanks for the tips 🙂
Excellent!!! I was looking for this, 😉 thnx
Awesome, thanks for the post.
django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet.
I followed what you’re saying exactly. but I got this.
Please let me know how to solve this problem.
jinsu jang, add “import django” after os.environ.setdefault and “django.setup()” before importing models.
sys.path.append(os.path.join(os.path.dirname(__file__), ‘my_project’))
os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “my_project.settings”)
import django
from django.conf import settings
django.setup()
from my_app.models import MyModel