KEMBAR78
Topic 2-Database-Create-Read-Update-Delete-PK-FK | PDF | Relational Database | Databases
0% found this document useful (0 votes)
52 views41 pages

Topic 2-Database-Create-Read-Update-Delete-PK-FK

The document discusses database concepts and Django models. It explains what a database and ORM are. It also describes how to define models in Django and perform CRUD operations like creating, reading, updating and deleting data from tables using models.

Uploaded by

Raziq Ridzuan
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)
52 views41 pages

Topic 2-Database-Create-Read-Update-Delete-PK-FK

The document discusses database concepts and Django models. It explains what a database and ORM are. It also describes how to define models in Django and perform CRUD operations like creating, reading, updating and deleting data from tables using models.

Uploaded by

Raziq Ridzuan
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/ 41

Topic 2 :

Database
Django: models
- ORM
- Work with models
in Django
What is Database ?

• database is information that is set up for


easy access, management and updating.
• Databases are used for storing, maintaining
and accessing any sort of data.
• That information is gathered in one place so
that it can be observed and analyzed.
• Databases can be thought of as an organized
collection of information.
• database is a systematic collection of data that
support electronic storage and manipulation of
data
Pinciples of ORM

ORM (Object Relational Mapping)

- Uses the concept of Object-Oriented Programming to


organize database.

- By using ORM, we only need to know the method to be used in


database instead of using query (SQL).

- Combines the benefits of OOP and RDBMS


▪ Precludes the need for writing SQL
▪ Generates and executes DDL and DML as needed
▪ Provides flexibility w.r.t. mapping strategies
• technique that creates a layer between the language
and the database, helping programmers work with
data without the OOP paradigm.
OBJECT • provides an object-oriented layer between relational
databases and object-oriented programming
RELATIONAL languages without having to write SQL queries.
MAPPING (ORM) • bridge between databases and object-oriented
programming.
• The ORM equips user with object-oriented tools to
run commands that user would usually run on
databases.
• It masks out the complicated intricacies of the
databases and lets user manipulate them with user
own choice of programming language (must support
object-oriented programming).
ORM vs Relational Database (1/2)
▪ Objects are first-class citizens: “Think like an object”
▪ Relation / Table  Class
▪ Record / Row / Tuple  Object
▪ Attribute / Column  Properties/Member / Field
▪ Relationship  Composition / Aggregation
▪ Hierarchy (Is-A)  Inheritance
ORM vs Relational Database (2/2)

Relational ORM

Table Class
Column in table Property / Attribute
Query Method

Row in table Object


• A model is the single, definitive source of information about data.
Model • It contains the essential fields and behaviors of the data storing.
• Generally, each model maps to a single database table.
• Models define the structure of stored data, including the field types
and possibly also their maximum size, default values, selection list
options, help text for documentation, label text for forms, etc.
• Model is independent of the underlying database. Just write our
model structure and other code, and Django handles all the work of
communicating with the database for us.
Model • The model is the part of the Django code that will manage
the data part. It has the following information:
a) Table (table) in our project
b) Attributes (columns) in each table, as well as the information is a maximum
character example, if it is unique or not
c) Relationship between tables (relationship)

• Usually a class has information about a table.


 Model (Connection to
database, retrieving data from
database)

 View - UI Representation

 Controller = Connect Model and


View, Perform logic, business
rules of the applicatiom
MVC flow

Routes … -> Routes dapatkan information, contohnya


en-gb / hotels / hotel-ibis-kuala lumpur
Controller -> will get the data from database.
For example : SELECT * FROM hotels WHERE
hotel_name = hotel-ibis-kuala-lumpur
Controller retrieve the data, add some logic , for
example: get the reviews, get images
All is passed to View and View will render it in the UI
MVT (DJANGO FRAMEWORK)

Model - Everything that is


related to Database
(Model)
View -> Logic , business rules
, connect model and
template
Template - UI,
Representation, layout
What is Model in Django?

Model is a part of Django code that will organize data and database.
It consist of:
a) Table in the project
b) Property / attribute / column:
➢ data types
➢ maximum number of character (max field length)
➢ null / not null value

c) Relationship between tables


Model Field Types
▪ AutoField
▪ EmailField ▪ PositiveSmallIntegerField
▪ BigAutoField
▪ FileField ▪ SlugField
▪ BigIntegerField ▪ FilePathField ▪ SmallIntegerField
▪ BinaryField ▪ FloatField ▪ TextFIeld
▪ BooleanField ▪ ImageField ▪ TimeField
▪ CharField ▪ IntegerField ▪ URLField
▪ DateField (yyyy-mm- ▪ GenericIPAddressField ▪ ForeignKey
dd) ▪ NullBooleanField ▪ Primary Key
▪ PositiveIntegerField ▪ ManyToManyField
▪ DateTimeField
▪ OneToOneField
▪ DecimalField
▪ DurationField https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-types
Important files will be generated
models.py -> To define our model
(data in database)
views.py -> Controller (logic of our
application)
Defining a table
SQL: models.py:

CREATE TABLE Users( from django.db import models


name VARCHAR(128),
email VARCHAR(128) Class User(models.Model):
); name = models.CharField(max_length=128)
email = models.CharField(max_length=128)
How to create
table
How to create table
1. Create project name KPMB
2. Runserver
3. Create application Registration
4. Open Visual code
5. Edit setting in main project (KPMB) - INSTALLED_APPS

6. Save setting.py
How to create table
7. Edit models.py in subproject (Registration)
 Create table Course with attribute
o code (datatype = char, length=4, primary key)
o description (datatype=text)
How to create table
7. Save models.py
8. Go to command prompt
➢ python manage.py makemigrations
(makemigrations is responsible for packaging up your model changes into individual
migration files - analogous to commits.
➢ Table Course is created in your project
➢ python manage.py migrate (migrate executes those SQL commands in the database file.
So after executing migrate all the tables of your installed apps are created in your database file.)
How to view table
10.Go to Visual code
11. Go to SQLITE EXPLORER –
➢ Right hand click at dbsqlite3 – open Database
click Register_course
Table is not displayed because no
objects has been added to the table
HOW TO ADD
EXTENSION SQLITE
(To view database in
Visual Studio Code)
Add Extension in VSC

2. Search
1. Click SQLite
here
How to add data
to table
How to add data to table
1. Go to command prompt
 Use Python interpreter (Python shell) to add data in table
o python manage.py shell

2. Import table in subproject models


➢ from Registration.models import Course

3. Add data
➢ data=Course('DCS', description='Diploma in Computer Science')
➢ data.save( )
How to add data to table

4. Display data
 Use Python interpreter (Python shell) to add data in table
o Course.objects.all( ).values( )

5. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_course
➢ Right hand click show tables
How to delete
data in table
How to delete data in table

1. Go to command prompt
 Use Python interpreter (Python shell) to add data in table
o python manage.py shell

2. Import table in subproject models


➢ from Registration.models import Course

3. delete data
➢ Course.objects.get(code='DCS').delete()
How to delete data in table
4. Display data
 Use Python interpreter (Python shell) to delete data in table
o Course.objects.all( ).values( )

5. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_course
➢ Right hand click show tables
How to display
data in table
How to display all data in table
1. Stay in shell in command prompt
2. Display all data
 Use Python interpreter (Python shell) to display all data in table
o Course.objects.all( ).values( )

3. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_course
➢ Right hand click show tables
How to display specific data in table
1. Stay in shell in command prompt
2. Display specific data
 Use Python interpreter (Python shell) to display specific data in table
o Course.objects.filter(code='DCS').values()

3. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_course
➢ Right hand click show tables
How to update
data in table
How to update data in table
1. Stay in shell in command prompt
2. Display all data
 Use Python interpreter (Python shell) to add data in table
o Course.objects.all( ).values( )

3. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_course
➢ Right hand click show tables
How to update data in table
1. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_course
➢ Right hand click show tables

2. Go to command prompt
3. Stay in shell in command prompt
4. Update specific data
 Use Python interpreter (Python shell) to update data in table
o Course.objects.filter(code = 'DCS').update(description = 'Diploma in Computer SC')
How to create
table with
primary key and
foreign key
How to create table
1. Edit models.py in subproject (Registration)
 Create table Student with attribute
o id (datatype = char ,length=12, primary_key)
o name (datatype = char ,length=100)
o address (datatype = char ,length=150)
o phone (datatype = char ,length=12)
o course_code (ForeignKey)

2. Save models.py
3. Go to command prompt
➢ python manage.py makemigrations
➢ Table Student is created in your project
➢ python manage.py migrate
How to create table
10.Go to Visual code
➢ Right hand click at dbsqlite3 – open Database 11. Go to SQLITE EXPLORER –
click Register_student
How to add data to table with foreign key
1. Go to command prompt
 Use Python interpreter (Python shell) to add data in table
o python manage.py shell

2. Import table in subproject models


➢ from Registration.models import Course, Student

3. Add data
➢ a=Course.objects.get(code='DIA')
➢ >>> data1 = Student (id='S002', name = 'azie binti nasir',address='batu gajah
perak',phone='017-222', course_code=a)
➢ >>> data1.save()
How to add data to table with foreign key (view)
4. Go to Visual Code
➢ Go to SQLITE EXPLORER – click Register_student
➢ Right hand click show tables

You might also like