views:

1307

answers:

3

I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?

+5  A: 

You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):

import os

os.environ['PYTHONPATH'] = '/path/to/myproject'
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

Now you should be able to access the models:

from myproject.models import MyModel

all_my_models = MyModel.objects.all()
Soviut
We do this with plain-old environment variables in the shell.
S.Lott
This does not work. Python reads PYTHONPATH on startup.http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH
Andrew Austin
Just to clarify, instead of trying to set PYTHONPATH, you want to use something like sys.path.append("/usr/local/django/") to use your project path.
Andrew Austin
+3  A: 

Depending on your specific needs, django-command-extensions might save you a bit of time. To run any script as-is without messing around with environment variables just type:

./manage.py runscript path/to/my/script.py

django-command-extensions also has commands for automating scripts as cron jobs, which is something you mentioned that you'd like to do.

If you are a more nuts and bolts type of person, you might check out this very detailed post outlining how to make "standalone" django scripts to be run from cron jobs and whatnot.

Prairiedogg
+8  A: 

The preferred way should be to add a custom command and then run it as any other django-admin (not to be confused with django.contrib.admin) command:

./manage.py mycustomcommand --customarg

Setting DJANGO_SETTINGS_MODULE should only be used when a custom command is not feasible.

muhuk
+1 - this is the best way to do it, as your command can be nicely integrated with the rest of the app and easily run using manage.py. Docs here: http://docs.djangoproject.com/en/dev/howto/custom-management-commands/
Carl Meyer
+1 Unfortunately the official documentation is a bit light on the implementation details and refers you do read the source. This is not a bad thing, but if you want a quick fix, take a look at http://www.b-list.org/weblog/2008/nov/14/management-commands/ which has a working example.
Andre Miller
Oh, another Django dev also has a blog explaining the process, here: http://oebfare.com/blog/2008/nov/03/writing-custom-management-command/
Andre Miller