Django Models
Models, Migration,
ORM
Program: EDGE-CSE CUET DIGITAL Instructor:
SKILLS TRAINING Tanveer Rahman,
Sr. Software Engineer,
Course: Python (Django) [Intermediate]
Friends Corp.
Lecture: Training Session-07 Chuo-ku, Tokyo, JP
Date: 7th October, 2024 shakil10vr@[Link],
Duration: (2+2) hours 01626735005
Agenda
Hands-on
Tasks:
Django
Creating
Models, Understan Advanced
Relationshi
Model ding ORM
p in
Fields, Migrations Queries
Models,
Queries
Custom
Queries
A model in Django is a
class that defines the
structure of database
Models
tables. serve as a
blueprint for database
tables and define the
Django fields and behaviors of the
Models data being stored.
Importance of Models:
• Simplifies database management.
• Enables automatic generation of
queries using Django's ORM.
• Reflects real-world data and
relationships.
Creating Models
in Django
• Defining a Model
• Models are Python classes that inherit from
[Link].
• Fields are defined as class attributes.
• Example: Basic Model
Common Field Types
CharField: For short text (e.g.,
titles, names).
Model IntegerField: For numbers.
Fields in DateField: For date values.
BooleanField: For True/False
Django values.
• ForeignKey: To define
Example:
relationships between
models.
• class Author([Link]):
name = [Link](max_length=100)
What is
Django ORM?
The Django ORM
Django (Object-Relational
Mapping) allows
ORM you to interact
with the database
using Python code
instead of SQL.
Querysets are used
Basic ORM
Queries
• Retrieve all
Django records:
ORM • books =
[Link](
Queries )
• Filter records:
• books =
[Link]
r(author="John
Doe")
•
What Are Migrations?
Migrations are Django's way of
Understa propagating changes you make to
models (adding a field, deleting a
nding model, etc.) into your database
schema.
Migration • Migrations help manage the
Commands
schema andforkeep it
s Migrations:
synchronized with your models.
• Create migrations:
• python [Link] makemigrations
• Apply migrations:
• python [Link] migrate
Types of
Relationships:
Creating OneToOneField:
One-to-one
Relations relationship
hips in between two
Models models.
ForeignKey:
Example: Many-
to-one relationship.
• ManyToManyField:
Many-to-many
Task 1 -
•Create two models: Author
Create and Book.
Basic •Add fields to the Author
model: name, birthdate.
Models •Add fields to the Book model:
title, publication_date, and a
(Duration ForeignKey to Author.
•Run the migration to create the
: 30 mins) corresponding database tables.
Aggregations
• Calculate average, sum, count, etc.:
• from [Link] import Avg,
Advanced Count
• avg_price =
ORM
[Link](Avg('price'))
Ordering and Slicing
Queries • Ordering:
• books = [Link].order_by('title')
• Limit the number of results:
• books = [Link]()[:5]
Model Managers and
Custom Queries
Model Managers Example:
• The default
manager in
Django is
objects. You can
create custom
managers to
Model Methods
Adding Custom
Methods to Example:
Models
• You can define
custom
methods in a
model to
encapsulate
Task 2 -
•Retrieve all books by a
Querying specific author.
Data •Filter the books that were
published in the last 5 years.
Using ORM •Sort books by price in
(Duration: descending order.
•Calculate the average price of
30 mins) all books.
What is a Queryset?
• A queryset is a collection of
database queries to retrieve
Understa objects from the database.
Lazy Evaluation
nding • Querysets are not evaluated
Django until they are specifically
iterated over, making them
Querysets highly efficient.
Chaining Queries
• Queries can be combined and
optimized:
books = [Link](author="John
Doe").order_by('-published_date')
Task 3 -
Model •Add a Publisher model and
link it to the Book model using
Relations a ForeignKey.
•Write queries to list all books
hips from a specific publisher.
•Write a query to count how
(Duration many books a particular
: 40 mins) publisher has published.
Use meaningful model names.
Leverage Django's built-in
validation features (like
Best max_length).
Practices Avoid putting too much logic
in the models; keep it focused
on data.
Optimize your queries using
select-related and prefetch-
related.
Task 4 - •Create models for Author, Book,
Complete and Publisher.
•Define appropriate fields and
Model relationships.
•Write Django ORM queries to:
Applicatio •Get all books by a specific author.
n •Find the publisher with the highest
number of books.
(Duration: •Calculate the total number of books
published in the last year.
•Run migration, perform CRUD
1 hour) operations using Django ORM.
Models: Define database
structure using Python classes.
Migrations: Automatically
handle schema changes
(makemigrations, migrate).
Recap ORM: Interact
Key queries: all(),
filter(), get().
with the database Relationships:
using Python, ForeignKey,
ManyToManyField,
avoiding SQL. OneToOneField.
Created models
(e.g., Author,
Book).
Practical Task: Performed CRUD
operations and
queried data.
Q&A
Session