tags:

views:

42

answers:

3
+1  Q: 

Scripting Django

Hi, what is the best way to write a python script (not to run within a Django server app) making use of Django settings, models, utilities etc and hence being able to operate on an app database from, say, a batch process?

EDIT

I need to use this within another server to make rather complex operations on the database, so solutions like custom AppCommands or invoking a Djando page won't really work

Thanks

A: 

I would look into creating a custom administration command. The documentation for Django's custom AppCommands can be found here: http://docs.djangoproject.com/en/dev/howto/custom-management-commands/

Note that this applies to Django 1.2 and up.

Once created, the app command (let's assume it was saved in myApp/management/commands/example.py) can be run by invoking

manage.py example
Josiah
+4  A: 

One way to do this is to create your own management command. Then you can do something like this from e.g. your crontab:

python manage.py my_command

Another way is to make sure Django, your Django project and, when required, third party apps are on your PYTHONPATH. Then you can access the database and ORM using a few lines of code:

from django.core.management import setup_environ
from my_project import settings
setup_environ(settings)

Now you can e.g. do things like this:

from my_app.models import MyModel
all_objects = MyModel.objects.all()
Mark van Lent
+1  A: 

Various ways.

Ignacio Vazquez-Abrams