Django Shell is an interactive Python console with the full Django environment loaded.
Starting the Shell
python manage.py shell
Django initializes the project settings and app registry. Import the models you want to use, as shown below.
Core Operations
# Import models
from tasks.models import Task, Project
from django.contrib.auth.models import User
# Creating objects
user = User.objects.create_user('testuser', password='pass123')
project = Project.objects.create(name='My Project')
task = Task.objects.create(title='First Task', owner=user, project=project)
# Reading
Task.objects.all()
Task.objects.filter(status='todo')
task = Task.objects.get(pk=1)
# Updating
task.status = 'done'
task.save()
# Deleting
task.delete()
Debugging Queries
from django.db import connection
Task.objects.all()
print(connection.queries) # list of executed SQL queries
Testing Code
# Check business logic
task = Task.objects.first()
print(task.get_status_display())
print(str(task))
# Inspect a queryset
qs = Task.objects.select_related('project').filter(owner__username='testuser')
print(qs.query) # show the SQL
IPython Shell (Enhanced)
pip install ipython
python manage.py shell # automatically uses IPython
Features: tab completion, command history, syntax highlighting, ? for help.
shell_plus (django-extensions)
pip install django-extensions ipython
# settings.py
INSTALLED_APPS = [
...,
'django_extensions',
]
python manage.py shell_plus
# Automatically imports ALL models!
On startup, all models are imported automatically:
from tasks.models import Task, Project
from django.contrib.auth.models import User
# and every other model from every app
With IPython (recommended)
python manage.py shell_plus --ipython
IPython features: Tab completion, ? and ?? for docs, syntax highlighting, command history.
In [1]: Task? # class help
In [2]: Task.objects. # Tab to autocomplete methods
In [3]: print(Task.objects.all().query) # inspect generated SQL
In [4]: %run script.py # load a script
Jupyter Notebook
python manage.py shell_plus --notebook
Opens a Jupyter Notebook with the full Django environment โ great for data analysis.
Other useful django-extensions commands
python manage.py graph_models -a -o models.png # diagram of all models
python manage.py show_urls # list all URLs
python manage.py runserver_plus # werkzeug debugger
python manage.py create_command myapp # scaffold a management command
Running a Script
python manage.py shell < script.py
# or
python manage.py shell -c "from tasks.models import Task; print(Task.objects.count())"
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!