Django Django from the command line. Django from the command line.


Example

Supposing you have setup a django project, and the settings file is in an app named main, this is how you initialize your code

import os, sys

# Setup environ
sys.path.append(os.getcwd())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

# Setup django
import django
django.setup()

# rest of your imports go here

from main.models import MyModel

# normal python code that makes use of Django models go here

for obj in MyModel.objects.all():
    print obj

The above can be executed as

python main/cli.py