Skip to content

Using Django Models In Batch Jobs

by Paul Kenjora on July 4th, 2007

If you want to run batch jobs that support your Django website the model interface is very handy. You may even use templates with this approach. Here is the basic setup to run Django applications from the command line.

batch.py


#!/home/username/lib/python2.4
import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'arkayne.settings'
sys.path.append(os.path.abspath('/home/someuser/django'))
sys.path.append(os.path.abspath('/home/someuser/lib/python2.4'))

from arkayne.arkayne.models import Page

def main(argv):
pages = Page.objects.all()
for page in pages:
print page.url

if __name__ == "__main__":
main(sys.argv[1:])

  • I agree with SuperJared, there are easier methods but I cant tell you how many times ive fought with PYTHONPATH and DAJNGO_SETTINGS_MODULE to get the other method working.

    This approach works 100% no matter what shell, user, configuration you have. You still need access to Django of course.
  • If this script is running in a location where your settings.py is accessible, you can simplify the Django environment setup like so:

    # setup Django environment
    import settings # your settings module
    from django.core import management
    management.setup_environ(settings)

    No need to muck with os.environ or DJANGO_SETTINGS_MODULE.
blog comments powered by Disqus