0% found this document useful (0 votes)
30 views17 pages

Django CheatSheets

Uploaded by

sagarc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views17 pages

Django CheatSheets

Uploaded by

sagarc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

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 manage.py runserver

Django Project Structure


manage.py: Command-line utility for administrative tasks.

settings.py: Contains project configurations.

urls.py: Defines URL routing.

wsgi.py: Used for deploying the application.

asgi.py: For asynchronous server support.

First Django App

python3 manage.py startapp app_name

Add app name into INSTALLED_APPS in settings.py

INSTALLED_APPS = [
...,
"app_name",
]

Writing Views

// views.py

from django.shortcuts import render


from django.http import HttpResponse

Django CheatSheet 2
def home(request):
return HttpResponse("Hello World!")

Mapping URL to Views

// project urls.py

from django.contrib import admin


from django.urls import path, include

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.

from django.db import models

class UserProfile(models.Model):
user = models.OneToOneField('auth.User', on_delete=model
s.CASCADE)
bio = models.TextField()

def __str__(self):
return self.user.username

OneToOneField creates a one-to-one relationship.

on_delete=models.CASCADE 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(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

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(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

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 django.contrib.contenttypes.fields import GenericForeign


Key
from django.contrib.contenttypes.models import ContentType

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:

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 django.db import models

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:

Models represent database tables, and each model field corresponds to a


database column.

Use python manage.py makemigrations and python manage.py migrate to create and
apply database changes.

3. Resetting the Database


To reset the database:

1. Run migrations:

python manage.py makemigrations


python manage.py migrate

2. Clear existing data:

Django CheatSheet 8
python manage.py 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 = Author.objects.all()

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 = Author.objects.all()

Retrieve a single object:

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.

Use filter() for safe retrieval of multiple objects.

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.

Chain multiple filters to refine results further.

7. Complex Lookups Using Q Objects


Combine queries using Q objects:

from django.db.models import Q

results = Author.objects.filter(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 django.db.models import F

results = Author.objects.filter(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 = Author.objects.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 = Author.objects.all()[: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 = Author.objects.only('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 = Author.objects.defer('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 = Book.objects.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 django.db.models import Avg

average_age = Author.objects.aggregate(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 django.db.models import Count

authors = Author.objects.annotate(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 django.db.models.functions import Lower

authors = Author.objects.annotate(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 = Book.objects.values('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 django.db.models import ExpressionWrapper, F, DecimalFie


ld

data = Book.objects.annotate(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 django.contrib.contenttypes.fields import GenericForeign


Key
from django.contrib.contenttypes.models import ContentType

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:

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(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:

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 = Author.objects.all()

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 = Author.objects.create(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 = Author.objects.get(id=1)
author.name = "Jane Doe"
author.save()

Must-Know:

Use update() for bulk updates.

Always call save() after modifying an object.

24. Deleting Objects


Delete entries:

Django CheatSheet 16
author = Author.objects.get(id=1)
author.delete()

Must-Know:

Use delete() cautiously as it removes data permanently.

QuerySet.delete() allows bulk deletions.

25. Transactions
Ensure atomicity with transactions: Group of operation gets rollback if any
operation failed.

from django.db import transaction

with transaction.atomic():
author = Author.objects.create(name="New Author")
Book.objects.create(title="New Book)

Django CheatSheet 17

You might also like