Building a Data
Model
Models in Django
• Storing data in a database is a common practice in
most web applications.
• In Django data and tables are represented in
models.
• A model contains the field and behaviors of the
data
• Commonly, each model maps to a database table.
• By creating models in the app models.py module,
Django automatically create database tables for
these models.
2
StoreProject Data Model 0 .. 1
featured_product
Product
Cart Category
title
* * 1
description *
created_at name
price products
inventory
1
1 1
*
CartItem *
* *
quantity OrderItem
quantity
Customer *
*
Order
name 1 *
email
placed_at 1
birth_date
…
3
StoreProject Data Model 0 .. 1
featured_product
Product
Cart Category
title
description * 1
created_at name
price products
inventory
1
1 1
CartItem *
* *
quantity OrderItem
quantity
Customer *
Order
name 1 *
email
placed_at 1
birth_date
…
4
The store APP
• When deciding to put the models in which app we need
to consider:
• Apps should be highly focused (models are cohesion)
• minimal coupling between the apps
• In our case we only need one app, let’s create it:
• In VSCode terminal:
python manage.py startapp store
• add the new app to the list of INSTALLED_APPS in project
settings
5
Django Model Basics
• Each model is a class that extends (inherits)
django.db.models.Model
• Each model attribute represents a database column (field)
• Django provides us with a set of useful methods to create,
update, read, and delete (CRUD) model information from
the database
• You can define custom methods on a model to add custom
“row-level” functionality to your objects.
• Manager methods are intended to do “table-wide” things,
model methods should act on a particular model instance.
6 https://docs.djangoproject.com/en/4.1/topics/db/models/
Creating Models
• Open the models.py module in the app folder.
• Write a class for each model describing the attributes of
the class. Example:
• For different field types and their options, check:
https://docs.djangoproject.com/en/4.1/ref/models/fields/
7
Exercise
Create class Customer with these fields:
• first_name
• last_name
• email (unique)
• phone
• birth_date (nullable)
8
Choice Fields
Sometimes we want the field values to be limited to specific values.
• Define a constant variable that is a list of tuples.
• Each tuple is a pair of two values. The first value is the actual value to be
used in the model, and the second value is a human-readable name.
• Define your field and set the choices option to the constant list.
9
Exercise
Create class Order with these fields:
• placed_at (datetime – auto populated at creation time)
• payment_status – Char field with these values:
• P = Pending
• C = Complete
• F = Failed
10