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-admincommands:
- You can display the help page for each
django-admincommand:
- To start a project:
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:
Migrations
Each migration is a Python script that makes a change to the database.
- Show list of migrations:
- Create migration files:
makemigrations generates Python code that represents the steps needed to get the database to the right state.
- Run migrations:
This will run all the pending migration files.
- See the actual SQL that a migration will run:
- Revert migrations:
If reverting to the initial migration, you use zero. Otherwise, specify the prefix of the migration file name corresponding to the migration number:
- Create an empty/custom migration file to do something specific:
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:
Note: If
start_migration_nameandend_migration_nameare omitted, all the migrations for the app are squashed.
Database Interaction
There are two primary ways to interact with databases in Django:
- Connect to the database shell:
The dbshell command provides direct access to the database configured in settings.py.
- Use object managers via
Model.objects: .get(): Returns one object from the database. RaisesDoesNotExistif not found.
.filter(): Returns aQuerySetwhich can contain zero or multiple results.
>>> CustomUser.objects.filter(is_staff=False)
<QuerySet [<CustomUser: seconduser>, <CustomUser: thirduser>]>
Creating Objects from the 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.
Print Out the Raw Query
You can inspect the underlying SQL of a QuerySet using the query attribute: