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 python, 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
11/8/2011 7:30:40 PM

Accepted Answer

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.

11/8/2011 7:37:40 AM

Since Django 1.4 you should avoid using setup_environ(settings) (post by Melug) because it is deprecated. Use the following instead and you will be able to access your model

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

# your imports, e.g. Django models
from your_project_name.models import Location

# From now onwards start your script..

Here is an example to access and modify your model:

if __name__ == '__main__':    
    # e.g. add a new location
    l = Location() = 'Berlin'

    # this is an example to access your model
    locations = Location.objects.all()
    print locations

    # e.g. delete the location
    berlin = Location.objects.filter(name='Berlin')
    print berlin

Example model:

class Location(models.Model):
    name = models.CharField(max_length=100)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow