15👍
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()
13👍
The preferred way should be to add a custom command and then run it as any other django-admin
(not to be confused with django.contrib.admin
) command:
./manage.py mycustomcommand --customarg
Setting DJANGO_SETTINGS_MODULE should only be used when a custom command is not feasible.
- Resolving AmbiguousTimeError from Django's make_aware
- How to specify uniqueness for a tuple of field in a Django model
- Request input from django custom command?
- How to use full_clean() for data validation before saving in Django 1.5 gracefully?
- Invert boolean field in update operations with F()
5👍
Depending on your specific needs, django-command-extensions might save you a bit of time. To run any script as-is without messing around with environment variables just type:
./manage.py runscript path/to/my/script.py
django-command-extensions also has commands for automating scripts as cron jobs, which is something you mentioned that you’d like to do.
If you are a more nuts and bolts type of person, you might check out this very detailed post outlining how to make “standalone” django scripts to be run from cron jobs and whatnot.
- Django Rest Framework: Serialize data from nested json fields to plain object
- Django global variable
- Is there a way to check whether a related object is already fetched?
- Django admin many-to-many intermediary models using through= and filter_horizontal
- Setup.py exclude some python files from bdist