2

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

3 Answers 3

6

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()
Sign up to request clarification or add additional context in comments.

1 Comment

setup_environ is gone in recent versions of Django.
2

setup_environ was deprecated since 1.4. You can use this way:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'yoursite.settings'
import django
django.setup()

Then you can use your models.

from my_app.models import MyModel
all_objects = MyModel.objects.all()

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.