Date: 2021-11-27
If you want to quickly use the Django ORM to query something or run some function in your codebase, you have three options:
Drop into a Django shell using
python manage.py shell.
Annoying if you want to run the script multiple times.
Write a custom management command.
Quite a bit of work to set up.
A straight forward script that tries to import something from your Django codebase would quickly be met by the following error:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.This error occurs because Django requires an initialization step where it loads the settings and runs the initialization for each registered Django app. We can initialize Django with two simple lines:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
import django
django.setup()
# do anythingAfter django.setup() has been called, the app is fully
initialized and you can safely import anything from your codebase
without having a AppRegistryNotReady error thrown in your
face.