Django CheatSheets
Django CheatSheets
What is Django?
Django is a high-level Python web framework that encourages rapid development
and clean, pragmatic design. It follows the Model-View-Template
(MVT) architectural pattern and comes with many built-in features to reduce
development time.
Setting Up Django
1. Install Django:
Django CheatSheet 1
python3 manage.py runserver
INSTALLED_APPS = [
...,
"app_name",
]
Writing Views
// views.py
Django CheatSheet 2
def home(request):
return HttpResponse("Hello World!")
// project urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("app.urls"))
]
// app urls.py
from django.urls import path
from .views import home
urlpatterns = [
path("home", home)
]
Creating Models
class Product(models.Model):
name = models.CharField(max_length=200) # String with a max
description = models.TextField(blank=True) # Large text, op
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.IntegerField() # Integer field
available = models.BooleanField(default=True) # Boolean fie
category = models.CharField(
max_length=50,
Django CheatSheet 3
choices=[
('ELECTRONICS', 'Electronics'),
('FASHION', 'Fashion'),
('FOOD', 'Food'),
]
) # Choice field
created_at = models.DateTimeField(auto_now_add=True) # Auto
updated_at = models.DateTimeField(auto_now=True) # Auto-fil
def __str__(self):
return self.name
Django Relationships
One-to-One Relationships: A one-to-one relationship means that one record
in a table is related to exactly one record in another table.
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', on_delete=model
s.CASCADE)
bio = models.TextField()
def __str__(self):
return self.user.username
Django CheatSheet 4
One-to-Many Relationships: A one-to-many relationship means that one
record in a table can be related to multiple records in another table.
Example:
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCA
DE)
def __str__(self):
return self.title
class Student(models.Model):
name = models.CharField(max_length=100)
Django CheatSheet 5
def __str__(self):
return self.name
class Course(models.Model):
title = models.CharField(max_length=200)
students = models.ManyToManyField(Student)
def __str__(self):
return self.title
Example:
class Tag(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class TaggedItem(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
Django CheatSheet 6
content_type = models.ForeignKey(ContentType, on_delete=m
odels.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'objec
t_id')
def __str__(self):
return f"{self.tag} tagged on {self.content_object}"
Explanation:
Django ORM
1. Introduction: Django ORM is a powerful tool that abstracts database operations
into Python objects. It allows developers to interact with databases using Python
code instead of raw SQL.
Key Features:
Cross-database compatibility.
Must-Know:
ORM abstracts raw SQL but is still capable of executing raw SQL when
needed.
ORM is tightly coupled with Django models and queries data through model
classes.
Django CheatSheet 7
2. Django ORM Basics
The ORM is tightly integrated with Django models, which define the structure of
your database tables.
Example:
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCA
DE)
published_date = models.DateField()
Must-Know:
Use python manage.py makemigrations and python manage.py migrate to create and
apply database changes.
1. Run migrations:
Django CheatSheet 8
python manage.py flush
Must-Know:
flush removes all data from the database and resets auto-incrementing
primary keys.
Example:
Must-Know:
QuerySets are lazy; they are evaluated only when data is accessed.
5. Retrieving Objects
Retrieve all objects:
authors = Author.objects.all()
author = Author.objects.get(id=1)
Must-Know:
Django CheatSheet 9
get() raises DoesNotExist exception if no match is found and
MultipleObjectsReturned if multiple matches exist.
6. Filtering Objects
Filter objects based on conditions:
adults = Author.objects.filter(age__gte=18)
Must-Know:
Double underscores ( __ ) are used to specify lookups like gte , lte , contains ,
etc.
Must-Know:
Useful for complex queries that cannot be expressed using standard filters.
Django CheatSheet 10
from django.db.models import F
results = Author.objects.filter(age__lt=F('books__published_y
ear'))
Must-Know:
9. Sorting Results
sorted_authors = Author.objects.order_by('name')
Must-Know:
limited_authors = Author.objects.all()[:10]
Must-Know:
Slice notation can limit results but evaluates the QuerySet immediately.
Django CheatSheet 11
authors = Author.objects.only('name')
Must-Know:
Reduces database load but increases query complexity if deferred fields are
accessed.
authors = Author.objects.defer('age')
Must-Know:
books = Book.objects.select_related('author')
Must-Know:
prefetch_related fetches related data in separate queries but caches results for
optimization.
Django CheatSheet 12
from django.db.models import Avg
average_age = Author.objects.aggregate(Avg('age'))
Must-Know:
authors = Author.objects.annotate(book_count=Count('book'))
Must-Know:
authors = Author.objects.annotate(lower_name=Lower('name'))
Must-Know:
Django CheatSheet 13
17. Grouping Data
Group data for calculations:
data = Book.objects.values('author__name').annotate(total_boo
ks=Count('id'))
Must-Know:
data = Book.objects.annotate(price_with_tax=ExpressionWrapper
(F('price') * 1.1, output_field=DecimalField()))
Must-Know:
class TaggedItem(models.Model):
Django CheatSheet 14
content_type = models.ForeignKey(ContentType, on_delete=m
odels.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'objec
t_id')
Must-Know:
class PublishedBooksManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_published=Tru
e)
class Book(models.Model):
...
objects = models.Manager() # Default manager
published = PublishedBooksManager() # Custom manager
Must-Know:
queryset = Author.objects.all()
Django CheatSheet 15
list(queryset) # Evaluates and caches the results
Must-Know:
Must-Know:
author = Author.objects.get(id=1)
author.name = "Jane Doe"
author.save()
Must-Know:
Django CheatSheet 16
author = Author.objects.get(id=1)
author.delete()
Must-Know:
25. Transactions
Ensure atomicity with transactions: Group of operation gets rollback if any
operation failed.
with transaction.atomic():
author = Author.objects.create(name="New Author")
Book.objects.create(title="New Book)
Django CheatSheet 17