Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How can I use my model classes to interact with my database from outside Django?

I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?

like image 219
Corey Avatar asked Dec 20 '08 07:12

Corey


1 Answers

You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):

import os

os.environ['PYTHONPATH'] = '/path/to/myproject'
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

Now you should be able to access the models:

from myproject.models import MyModel

all_my_models = MyModel.objects.all()
like image 115
Soviut Avatar answered Oct 22 '22 18:10

Soviut