Django CheatSheet
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.
Key Features of Django
Batteries-Included: Comes with features like authentication, ORM, admin
interface, and much more.
Scalability: Handles large projects with ease.
Security: Provides protection against SQL injection, CSRF, XSS, and
clickjacking.
Community Support: Extensive documentation and a large community.
Setting Up Django
1. Install Django:
pipenv install django
2. Create a Django project:
django-admin startproject project_name
3. Run the development server:
Django CheatSheet 1
python3 [Link] runserver
Django Project Structure
[Link]: Command-line utility for administrative tasks.
[Link]: Contains project configurations.
[Link]: Defines URL routing.
[Link]: Used for deploying the application.
[Link]: For asynchronous server support.
First Django App
python3 [Link] startapp app_name
Add app name into INSTALLED_APPS in [Link]
INSTALLED_APPS = [
...,
"app_name",
]
Writing Views
// [Link]
from [Link] import render
from [Link] import HttpResponse
Django CheatSheet 2
def home(request):
return HttpResponse("Hello World!")
Mapping URL to Views
// project [Link]
from [Link] import admin
from [Link] import path, include
urlpatterns = [
path("admin/", [Link]),
path("", include("[Link]"))
]
// app [Link]
from [Link] import path
from .views import home
urlpatterns = [
path("home", home)
]
Creating Models
class Product([Link]):
name = [Link](max_length=200) # String with a max
description = [Link](blank=True) # Large text, op
price = [Link](max_digits=10, decimal_places=2)
quantity = [Link]() # Integer field
available = [Link](default=True) # Boolean fie
category = [Link](
max_length=50,
Django CheatSheet 3
choices=[
('ELECTRONICS', 'Electronics'),
('FASHION', 'Fashion'),
('FOOD', 'Food'),
]
) # Choice field
created_at = [Link](auto_now_add=True) # Auto
updated_at = [Link](auto_now=True) # Auto-fil
def __str__(self):
return [Link]
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.
from [Link] import models
class UserProfile([Link]):
user = [Link]('[Link]', on_delete=model
[Link])
bio = [Link]()
def __str__(self):
return [Link]
OneToOneField creates a one-to-one relationship.
on_delete=[Link] ensures that when the
related User object is deleted, the UserProfile is also deleted.
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([Link]):
name = [Link](max_length=100)
def __str__(self):
return [Link]
class Book([Link]):
title = [Link](max_length=200)
author = [Link](Author, on_delete=[Link]
DE)
def __str__(self):
return [Link]
ForeignKey creates a one-to-many relationship.
An Author can have multiple Book entries, but each Book is
linked to a single Author .
Many-to-Many Relationships: A many-to-many relationship means that
multiple records in one table can relate to multiple records in another table.
class Student([Link]):
name = [Link](max_length=100)
Django CheatSheet 5
def __str__(self):
return [Link]
class Course([Link]):
title = [Link](max_length=200)
students = [Link](Student)
def __str__(self):
return [Link]
ManyToManyField creates a many-to-many relationship.
A Student can enroll in multiple Course entries, and a Course can
have multiple Student entries.
Generic Relationships: Generic relationships allow you to create relationships
to multiple models without specifying the model explicitly.
Example:
from [Link] import GenericForeign
Key
from [Link] import ContentType
class Tag([Link]):
name = [Link](max_length=50)
def __str__(self):
return [Link]
class TaggedItem([Link]):
tag = [Link](Tag, on_delete=[Link])
Django CheatSheet 6
content_type = [Link](ContentType, on_delete=m
[Link])
object_id = [Link]()
content_object = GenericForeignKey('content_type', 'objec
t_id')
def __str__(self):
return f"{[Link]} tagged on {self.content_object}"
Explanation:
GenericForeignKey allows the TaggedItem model to relate to any model.
ContentType is used to store the type of the related model.
object_id stores the primary key of the related object.
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:
Simplicity and readability.
Integration with Django models.
Support for complex queries.
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:
from [Link] import models
class Author([Link]):
name = [Link](max_length=100)
age = [Link]()
class Book([Link]):
title = [Link](max_length=200)
author = [Link](Author, on_delete=[Link]
DE)
published_date = [Link]()
Must-Know:
Models represent database tables, and each model field corresponds to a
database column.
Use python [Link] makemigrations and python [Link] migrate to create and
apply database changes.
3. Resetting the Database
To reset the database:
1. Run migrations:
python [Link] makemigrations
python [Link] migrate
2. Clear existing data:
Django CheatSheet 8
python [Link] flush
Must-Know:
flush removes all data from the database and resets auto-incrementing
primary keys.
Use cautiously in production environments.
4. Managers and QuerySets
Manager: Interface through which database queries are made. Default
manager is objects .
QuerySet: A collection of database queries.
Example:
# Using the default manager
authors = [Link]()
Must-Know:
Custom managers can be created to modify the default behavior of QuerySets .
QuerySets are lazy; they are evaluated only when data is accessed.
5. Retrieving Objects
Retrieve all objects:
authors = [Link]()
Retrieve a single object:
author = [Link](id=1)
Must-Know:
Django CheatSheet 9
get() raises DoesNotExist exception if no match is found and
MultipleObjectsReturned if multiple matches exist.
Use filter() for safe retrieval of multiple objects.
6. Filtering Objects
Filter objects based on conditions:
adults = [Link](age__gte=18)
Must-Know:
Double underscores ( __ ) are used to specify lookups like gte , lte , contains ,
etc.
Chain multiple filters to refine results further.
7. Complex Lookups Using Q Objects
Combine queries using Q objects:
from [Link] import Q
results = [Link](Q(age__gte=18) & Q(name__icon
tains="John"))
Must-Know:
Q objects allow OR ( | ) and AND ( & ) operations in filters.
Useful for complex queries that cannot be expressed using standard filters.
8. Referencing Fields Using F Objects
Compare fields in the same model:
Django CheatSheet 10
from [Link] import F
results = [Link](age__lt=F('books__published_y
ear'))
Must-Know:
F objects enable field-to-field comparisons.
They support arithmetic operations like addition, subtraction, etc.
9. Sorting Results
Sort query results:
sorted_authors = [Link].order_by('name')
Must-Know:
Use - before a field name to sort in descending order.
Combine multiple fields for complex sorting.
10. Limiting Results
Limit the number of results:
limited_authors = [Link]()[:10]
Must-Know:
Slice notation can limit results but evaluates the QuerySet immediately.
Use carefully in performance-critical code.
11. Selecting Fields to Query
Optimize queries by selecting specific fields:
Django CheatSheet 11
authors = [Link]('name')
Must-Know:
only() fetches specified fields, while others are deferred.
Reduces database load but increases query complexity if deferred fields are
accessed.
12. Deferring Fields
Exclude specific fields from the query:
authors = [Link]('age')
Must-Know:
Accessing deferred fields triggers a separate database query.
Use when specific fields are rarely accessed.
13. Selecting Related Objects
Fetch related objects efficiently using select_related or prefetch_related :
books = [Link].select_related('author')
Must-Know:
select_related performs a SQL join to fetch related data in a single query.
prefetch_related fetches related data in separate queries but caches results for
optimization.
14. Aggregating Objects
Perform aggregate calculations:
Django CheatSheet 12
from [Link] import Avg
average_age = [Link](Avg('age'))
Must-Know:
Aggregations return a dictionary with the result.
Common functions: Sum , Avg , Max , Min , Count .
15. Annotating Objects
Add calculated fields to query results:
from [Link] import Count
authors = [Link](book_count=Count('book'))
Must-Know:
Annotations can be used in filters and sorting.
Combine with aggregations for advanced queries.
16. Calling Database Functions
Use database functions like Lower or Upper :
from [Link] import Lower
authors = [Link](lower_name=Lower('name'))
Must-Know:
Functions like Concat , Length , Now , etc., are available.
Extend functionality by creating custom database functions.
Django CheatSheet 13
17. Grouping Data
Group data for calculations:
data = [Link]('author__name').annotate(total_boo
ks=Count('id'))
Must-Know:
values() creates a dictionary-like result, making it ideal for grouping.
Combine values() with annotate() for grouped calculations.
18. Working with Expression Wrappers
Use ExpressionWrapper for advanced expressions:
from [Link] import ExpressionWrapper, F, DecimalFie
ld
data = [Link](price_with_tax=ExpressionWrapper
(F('price') * 1.1, output_field=DecimalField()))
Must-Know:
ExpressionWrapper is essential for operations requiring output field specification.
Supports complex arithmetic and logic.
19. Querying Generic Relationships
Use GenericForeignKey for dynamic relationships:
from [Link] import GenericForeign
Key
from [Link] import ContentType
class TaggedItem([Link]):
Django CheatSheet 14
content_type = [Link](ContentType, on_delete=m
[Link])
object_id = [Link]()
content_object = GenericForeignKey('content_type', 'objec
t_id')
Must-Know:
Generic relationships allow linking a model to multiple other models.
Requires ContentType framework to track related models.
20. Custom Managers
Define custom managers for specific queries:
class PublishedBooksManager([Link]):
def get_queryset(self):
return super().get_queryset().filter(is_published=Tru
e)
class Book([Link]):
...
objects = [Link]() # Default manager
published = PublishedBooksManager() # Custom manager
Must-Know:
Custom managers modify the default QuerySet behavior.
Can include custom methods for frequently used queries.
21. Understanding QuerySet Cache
QuerySets are lazy but cache results after evaluation.
queryset = [Link]()
Django CheatSheet 15
list(queryset) # Evaluates and caches the results
Must-Know:
Cached QuerySets improve performance for repeated iterations.
Avoid modifying the database while iterating over cached QuerySets.
22. Creating Objects
Create new database entries:
new_author = [Link](name="John Doe", age=30)
Must-Know:
Use save() to create objects manually.
create() combines object creation and saving in one step.
23. Updating Objects
Update existing entries:
author = [Link](id=1)
[Link] = "Jane Doe"
[Link]()
Must-Know:
Use update() for bulk updates.
Always call save() after modifying an object.
24. Deleting Objects
Delete entries:
Django CheatSheet 16
author = [Link](id=1)
[Link]()
Must-Know:
Use delete() cautiously as it removes data permanently.
[Link]() allows bulk deletions.
25. Transactions
Ensure atomicity with transactions: Group of operation gets rollback if any
operation failed.
from [Link] import transaction
with [Link]():
author = [Link](name="New Author")
[Link](title="New Book)
Django CheatSheet 17