Using Django on CLI
Using Django for Non-Web Applications
Django is designed to be a web application framework. Unfortunately applications are not always purely ‘web-based’. Sometimes you need a background processing module that is clearly not web-based (CLI perhaps). Of course instead of reverting to plain SQL you would like to re-use your existing Django-based easy to use models and database API.
Basically all you need to do is to import your the settings module of your project (site) before importing your models. This allows Django to know which database to connect before hand. It is pretty much a tricky task but fortunately after digging core, I found a piece of code in django/core/management.py that might just do the trick.
And here what I got out of it. Just place this code in one of your Django app folder and its ready to go. You can then execute it like a regular any Python code.
#!/usr/bin/env python def setup_environ(): import os import sys # Expand the file path path_component = os.path.abspath(__file__).split(os.sep) # Add the project to sys.path so it's importable. project_name = path_component[-3] project_directory = os.sep.join(path_component[:-2]) sys.path.append(os.path.join(project_directory, '..')) project_module = __import__(project_name, {}, {}, ['']) sys.path.pop() # Set DJANGO_SETTINGS_MODULE os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project_name if __name__ == '__main__': setup_environ() # Import your Django models here import ProjectName.ApplicationName.models # Your code as usual ...
Notes:
- The script will need to reside in the same directory as your models.py. Despite that, you would need to state the complete import path when importing your models. i.e., import ProjectName.ApplicationName.models instead of just import models.
- This code will most likely also run on Windows :)
Feel free to tell me (comment below) if it works for you or if something is wrong :)
Good Luck and Have fun!