Trindaz Trindaz - 1 year ago 88
Python Question

Django script to access model objects without using shell

I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running

./ shell
and then
import myscript
. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using
, and in the first few lines of that script it would do whatever imports / other operations necessary so that it can access model objects and behave as though it was run using shell

What do I need to add to my script to achieve this?


Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:

import sys
from myproject import settings
from import setup_environ

Answer Source

You need to setup django environment first:

from your_project import settings
from import setup_environ

At last import your models, everything goes just like django.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download