100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Python Django Cheat Sheet

Python Django Cheat Sheet

Covers Django project and app setup, models, migrations, views, URL routing, and common ORM query patterns for building web applications.

2 PagesIntermediateApr 2, 2026

Project & App Setup

Scaffold a Django project and run the dev server.

bash
pip install django                       # Install Djangodjango-admin startproject mysite .       # Create project in current dirpython manage.py startapp blog           # Create an apppython manage.py runserver               # Run dev server (localhost:8000)python manage.py runserver 0.0.0.0:8080  # Run on custom host/port

Models

Define database tables as Python classes.

python
from django.db import modelsclass Post(models.Model):    title = models.CharField(max_length=200)    body = models.TextField()    published = models.BooleanField(default=False)    created_at = models.DateTimeField(auto_now_add=True)    author = models.ForeignKey(        "auth.User", on_delete=models.CASCADE, related_name="posts"    )    def __str__(self):        return self.title

Migrations

Generate and apply schema changes.

bash
python manage.py makemigrations        # Create migration files from model changespython manage.py migrate               # Apply migrations to the databasepython manage.py sqlmigrate blog 0001  # Preview SQL for a migrationpython manage.py showmigrations        # List migrations and their applied status

Views & URL Routing

Wire URLs to view functions and query the database.

python
# views.pyfrom django.shortcuts import render, get_object_or_404from .models import Postdef post_list(request):    posts = Post.objects.filter(published=True).order_by("-created_at")    return render(request, "blog/list.html", {"posts": posts})def post_detail(request, pk):    post = get_object_or_404(Post, pk=pk)    return render(request, "blog/detail.html", {"post": post})# urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [    path("", views.post_list, name="post_list"),    path("<int:pk>/", views.post_detail, name="post_detail"),]

Common ORM Queries

Frequently used QuerySet methods.

  • Model.objects.all()- Return a QuerySet of every row
  • Model.objects.get(pk=1)- Fetch a single object; raises DoesNotExist if none match
  • Model.objects.filter(field=value)- Return a QuerySet matching a condition
  • Model.objects.exclude(field=value)- Return objects that don't match a condition
  • .order_by('-created_at')- Sort results, prefix with '-' for descending order
  • .select_related('author')- Eager-load a ForeignKey in the same SQL query via JOIN
  • .prefetch_related('tags')- Eager-load a many-to-many/reverse-FK with a separate query
  • Model.objects.create(**kwargs)- Create and save a new row in a single call
Pro Tip

Use select_related() for ForeignKey/OneToOne fields and prefetch_related() for ManyToMany/reverse-FK fields to avoid the N+1 query problem — django-debug-toolbar makes it easy to spot in development.

Was this cheat sheet helpful?

Explore Topics

#PythonDjango#PythonDjangoCheatSheet#Programming#Intermediate#ProjectAppSetup#Models#Migrations#ViewsURLRouting#Databases#WebDevelopment#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet