WRITELOOP

HOW TO INTERACT WITH DJANGO MODELS OUTSIDE OF DJANGO

2014 November 11

Suppose you have a django project called “awesome”. It has an app named “core”, which has a model named “Client”. Then, inside the app “core”, you have a standalone script called “outsider.py” that is outside of django but has to consume the core model named “Client”. As follows: /tmp/awesome |– awesome | -- settings.py – core |– models.py `– outsider.py For that to work properly, you will have to add at the beginning of the file “outsider.py”: $ vim outsider.py from future import absolute_import import os import sys project_path = os.path.dirname(os.path.dirname(os.path.realpath(file)))

If the project is really outside of django you must hardcode the path:

project_path = ‘/tmp/awesome’

sys.path.append(project_path) os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “awesome.settings”)

for django 1.6 and below

from django.conf import settings

for django 1.7 and up

import django django.setup() To make the import you must explicitely point to the full model path (with the app name): $ vim outsider.py from core.models import Client IMPORTANT: as an alternative, you can also run the desired code within django’s manage shell: $ python manage.py shell … from core.outsider import my_method … my_method()