When working on a Django project, there are times when you need to process data directly against the project’s models and settings. In those situations, it is convenient to run a standalone script inside the Django environment instead of building a full command from scratch.
This post records a few ways to do that.
Django shell
Django’s built-in shell already loads the project environment, so a simple option is:
1 | python manage.py shell < script.py |
It is very simple, but it is not great when you want to pass arguments into the script, and it also does not work very naturally if your script is written around a main() function.
Custom management command
Another option is to create a small custom command. Here is a sample implementation I used recently. It can execute a target script file and pass through extra arguments.
1 | import os |
Put this file under any app’s management/commands directory and name it run_script.py.
After that, you can run a script like this:
1 | python manage.py run_script your_script arg1 arg2 -v arg3 |
django-extensions
You can also use the built-in runscript feature from django-extensions.
Reference:
https://django-extensions-zh.readthedocs.io/zh_CN/latest/runscript.html