Skip to content

Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MVT (Model-View-Template) architectural pattern.

A Django project comprises one or more Django applications, each serving a unique function.

django-admin

  • Display all available django-admin commands:
django-admin --help
  • You can display the help page for each django-admin command:
django-admin help <command_name>
  • To start a project:
django-admin startproject <project_name>

manage.py

Run server

Make sure to be in the folder where the manage.py file is located, then run the command to start the server:

python manage.py runserver

Migrations

Each migration is a Python script that makes a change to the database.

  • Show list of migrations:
python manage.py showmigrations
  • Create migration files:
python manage.py makemigrations

makemigrations generates Python code that represents the steps needed to get the database to the right state.

  • Run migrations:
python manage.py migrate

This will run all the pending migration files.

  • See the actual SQL that a migration will run:
python manage.py sqlmigrate <app_name> <migration_id>
  • Revert migrations:
python manage.py migrate tasks zero

If reverting to the initial migration, you use zero. Otherwise, specify the prefix of the migration file name corresponding to the migration number:

python manage.py migrate tasks 0021
  • Create an empty/custom migration file to do something specific:
python manage.py makemigrations tasks --empty
from django import migrations

def change_archived_tasks(apps, schema_editor):
    Task = apps.get_model("tasks", "Task")
    Task.objects.filter(status="ARCHIVED").update(status="COMPLETED")

class Migration(migrations.Migration):
    dependencies = [
        ("tasks", "0001_initial"),
    ]
    operations = [
        migrations.RunPython(change_archived_tasks)
    ]
  • Squashing migrations:
python manage.py squashmigrations app_name start_migration_name end_migration_name

Note: If start_migration_name and end_migration_name are omitted, all the migrations for the app are squashed.

Database Interaction

There are two primary ways to interact with databases in Django:

  1. Connect to the database shell:
python manage.py dbshell

The dbshell command provides direct access to the database configured in settings.py.

  1. Use object managers via Model.objects:
  2. .get(): Returns one object from the database. Raises DoesNotExist if not found.
>>> CustomUser.objects.get(id=1)
<CustomUser: admin>
  • .filter(): Returns a QuerySet which can contain zero or multiple results.
>>> CustomUser.objects.filter(is_staff=False)
<QuerySet [<CustomUser: seconduser>, <CustomUser: thirduser>]>

Creating Objects from the Shell

python manage.py shell
>>> from django.contrib.auth.models import User
>>> creator = User.objects.create_user("developer", "email@example.com", "password")

Data Migrations

Data migrations change the data but keep the migration schema unchanged. They are useful for mass updating objects.

You can inspect the underlying SQL of a QuerySet using the query attribute:

print(Task.objects.exclude(status='ARCHIVED').query)