SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
ORM in DJANGO
Hoang Nguyen
[Agenda]
ORM, What is?
and learn by hand 
[OOP, What does this mean?]
[Welcome to of Objects]
Each object is a Lego piece
This Lego bear sculpture contains over 95,000 LEGO pieces and took over 1100
hours to construct together.
This amazing Lego airport was showcased in LegoCity, at Senayan City,
Indonesia.
This machine has several playable features include functional powered treads for
movement, full suspension and front and rear steering. A true masterpiece.
Do you love Lego, too?
if you are programmer {
while (true) {
YOU OOP!
}
}
We also need persistence
[How we do persistence]
OOP languages provide object persistence
But it is fragile
Relational databases
Can store vast amounts of data in a structured way that allows for efficient
storage, access, and search
NoSQL solutions
truly vast datasets, real time and concurrent
[so, What problem]
Table Column RowClass Object Attrib-
ute
key – value
pairRelationMethod Inher-
itance
Associ-
ation
public const string ConnectionString =
@"Data Source=.Sqlexpress;Initial Catalog=Example;Integrated Security=SSPI;";
string sql = "select * from table where fname = '" + firstName + "' and lname
= '" + lastName + "'";
using (SqlConnection connection = new SqlConnection(ConnectionString)){
using (SqlCommand command = new SqlCommand(sql, connection)) {
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string output = "First Name: {0} t Last Name: {1} t Phone: {2}";
Console.WriteLine(output, reader["FirstName"], reader["LastName"],
reader["Telephone"]);
}
}
}
SELECT '%c%' as Chapter,
(SELECT count(ticket.id) as Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status IN
('new','assigned') ) AS 'New',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='document_interface' ) AS 'Document Interface',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='interface_development' ) AS 'Interface Development',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='interface_check' ) AS 'Interface Check',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='document_routine' ) AS 'Document Routine',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='full_development' ) AS 'Full Development',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='peer_review_1' ) AS 'Peer Review One',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%‘ AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='peer_review_2' ) AS 'Peer Review Two',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='qa' )
AS 'QA',
(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%‘ AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND
ticket.status='closed' ) AS 'Closed',
count(id) AS Total, ticket.id AS _id
FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine'
I am programmer.
I love OOP. I hate SQL.
You hear me. ORM is sexy.
[ORM, What is]
Object - Relational Mapping
type systems object-oriented
virtual object database
bunch of code
provides a set of APIs which allows access databases in OO style
helps database become more transparent
[ORM, What is]
1994: TopLink for SmallTalk – the first ORM
2001 – 2002: Hibernate
Entity Framework and LINQ
ACTIVE RECORD CORE DATA
Gavin King
[Discussion]
ORM is the Vietnam of Computer Science
http://blogs.tedneward.com/post/the-vietnam-of-computer-science/
https://blog.codinghorror.com/object-relational-mapping-is-the-vietnam-of-computer-science/
http://martinfowler.com/bliki/OrmHate.html
Trying to match two different world
How to work with ORM in
Django
[ORM in Django]
Save for insert and update
Delete for, well, delete
And some methods to load records
[How to create a model]
Must inherit from the Model class
Model class inside the models package (django.db.models.Model)
Model add ORM methods, such as save() and delete()
Model add an objects collection as a property for querying data
Create Student Model
[How to create a model]
property_name = models.Type(fieldOptions)
Type is some Field class inside models (you can create and use customize field classes)
Each property_name exactly is an instance of some field class
Each Field class represent a column type, which tells to the database what kind of
data to store.
fieldOptions is a set of field-specific arguments
[How to create a model]
[How to create string Field]
property_name = models.CharField(fieldOptions)
property_name = models.TextField(fieldOptions)
max_length: integer number represent maximum number of characters
null: bool value to indicate if null value is allowed. False by default.
blank: bool value to indicate if empty string is allowed. False by default.
default: default value if none is provided
choices: enumeration
[How to create number Field]
property_name = models.BigIntegerField(fieldOptions)
property_name = models.IntegerField(fieldOptions)
property_name = models.SmallIntegerField(fieldOptions)
property_name = models.PositiveIntegerField(fieldOptions)
property_name = models.PositiveSmallIntegerField(fieldOptions)
property_name = models.FloatField(fieldOptions)
null: bool value to indicate if null value is allowed. False by default.
default: default value if none is provided
[How to create Boolean Field]
property_name = models.BooleanField(fieldOptions)
property_name = models.NullBooleanField(fieldOptions)
null: bool value to indicate if null value is allowed. False by default.
default: default value if none is provided
[How to create date - time Field]
property_name = models.DateField(fieldOptions)
property_name = models.TimeField(fieldOptions)
property_name = models.DateTimeField(fieldOptions)
auto_now: automatically set the field to now every time the object is saved. False
by default. Note that the current date is always used; it’s not just a default value
that you can override.
auto_now_add: automatically set the field to now when the object is first created.
Note that the current date is always used; it’s not just a default value that you can
override.
[Some special fields]
A CharField that checks that the value is a valid email address. max_length=254
A CharField that checks that the value is a valid url. max_length=200
A CharField that checks that the value is a valid IP address.
protocol: both, IPv4, IPv6
unpack_ipv4: to convert a packed address(::ffff:192.0.2.1) to ipv4 address
(192.0.2.1)
[Some special fields]
upload_to: the string value will be appended to your MEDIA_ROOT path to form the
location on the local filesystem where uploaded files will be stored. upload_to may
also be a callable, such as a function
All that will be stored in your database is a path to the file (relative to MEDIA_ROOT).
You can get absolute path use mug_shot.url
Inherits all attributes and methods from FileField, but also validates that the uploaded
object is a valid image.
height_field=None, width_field=None
Read API reference for the other field types
ORM in Django
[How to create a primary key]
Must be unique for each record
Typically has a name of id
Typically is a auto-generate number
models.CharField(primary_key=True)
models.IntField(primary_key=True)
models.AutoField(primary_key=True)
[Exercise 1]
first_name: is a string, length <= 30, not null, not blank
mid_name: is a string, length <= 50, nullable, blankable
last_name: is a string, length <=30, not null, not blank
birthday: for storing the date of birth
admission_day: for storing the date and time
gender: F or M
class_name: is a string, length <= 50
special: is a string, length <=100
class_term: is a integer number
How about relationships?
[How to create relationships]
ForeignKey
ManyToManyField
OneToOneField
[How to connect to database]
[How to connect to database]
for details
SQLite
MySQL
Oracle
PostgreSQL
[How to sync between models and database]
Creates a package that contains all of the changes to be made on the database based
on the code changes in the models
--name
Synchronizes the database state with the current set of models and migrations
--fake
Prints the SQL for the named migration
[How to CRUD in OO style]
[How to CRUD in OO style]
[How to CRUD in OO style]
objects
objects
objects
objects
[How to Retrieve in OO style]
lazy
QuerySet has two public properties: ordered and db
Two main kinds of functions
return an instance of QuerySet class: all, filter, exclude, annotate, orderby, distinct, …
get, count, first, last, Avg, Count, Max, Min, Sum, Variance, StdDev, …
Example with get, all functions
[How to Retrieve in OO style]
[How to Retrieve in OO style]
values(‘property1’, ‘property2’, …) to select some properties
Lookup expression
Django is aware of your object structure => we can query data using the class structure we
created.
Use two underscore to call function or deeper property
String funcs: exact, contains, startswith, endswith, regex,
Use i prefix to call insensitive string funcs
Number funcs: gt, gte, lt, lte, range, …
Use in for list and subquery statements
Limiting QuerySet: [5], [:5], [5:10]
Examples with get, filter and exclude
[How to Retrieve in OO style]
How to make complex lookup expression
Chaining filters
Student.objects.filter(first_name__exact=‘Nguyen’).filter(last_name__exact=‘Hoang’)
Q() objects
&, |, ~
Q(first_name__exact=‘Nguyen’) & Q(last_name__exact=‘Hoang’)
Multiple update and delete
filters.delete()
filters.update(property1=value1, …)
filters.update(property1 = F(‘property1’) + 1, property2 = F(‘property3’) + 2)
“More like science. You grab this piece of library and you poke at it. You write
programs that poke it and see what it does. And you say, ‘Can I tweak it to do the
thing I want?’”
As to why they chose Python as an alternative, Sussman joked that it was “late
binding” decision. Python has a ton of libraries that make it applicable to many
types of projects that instructors might want to assign (like writing software to
control a robot.)

Más contenido relacionado

Was ist angesagt?

Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersRosario Renga
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoJay Graves
 

Was ist angesagt? (20)

Django
DjangoDjango
Django
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Python basic
Python basicPython basic
Python basic
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Javascript
JavascriptJavascript
Javascript
 
jQuery
jQueryjQuery
jQuery
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 

Andere mochten auch

PDXPortland - Dockerize Django
PDXPortland - Dockerize DjangoPDXPortland - Dockerize Django
PDXPortland - Dockerize DjangoHannes Hapke
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTTkevinvw
 
Develop with docker 2014 aug
Develop with docker 2014 augDevelop with docker 2014 aug
Develop with docker 2014 augVincent De Smet
 
Running Django on Docker: a workflow and code
Running Django on Docker: a workflow and codeRunning Django on Docker: a workflow and code
Running Django on Docker: a workflow and codeDanielle Madeley
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Djangoryates
 
Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansibleandrewmirskynet
 
Efficient Django
Efficient DjangoEfficient Django
Efficient DjangoDavid Arcos
 
AWS Elastic Beanstalk and Docker
AWS Elastic Beanstalk and DockerAWS Elastic Beanstalk and Docker
AWS Elastic Beanstalk and DockerDocker, Inc.
 

Andere mochten auch (10)

PDXPortland - Dockerize Django
PDXPortland - Dockerize DjangoPDXPortland - Dockerize Django
PDXPortland - Dockerize Django
 
Django via Docker
Django via DockerDjango via Docker
Django via Docker
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
 
Develop with docker 2014 aug
Develop with docker 2014 augDevelop with docker 2014 aug
Develop with docker 2014 aug
 
Running Django on Docker: a workflow and code
Running Django on Docker: a workflow and codeRunning Django on Docker: a workflow and code
Running Django on Docker: a workflow and code
 
Django and Docker
Django and DockerDjango and Docker
Django and Docker
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Django
 
Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansible
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
 
AWS Elastic Beanstalk and Docker
AWS Elastic Beanstalk and DockerAWS Elastic Beanstalk and Docker
AWS Elastic Beanstalk and Docker
 

Ähnlich wie ORM in Django

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Mike Nakhimovich
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
 
Odoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant TrainingAidIQ
 
Data Types & Objects .pptx
Data Types & Objects .pptxData Types & Objects .pptx
Data Types & Objects .pptxNayyabMirTahir
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talkdtdannen
 
Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsStefan Urbanek
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with DjangoSimon Willison
 

Ähnlich wie ORM in Django (20)

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Chapter 08
Chapter 08Chapter 08
Chapter 08
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
Arrays
ArraysArrays
Arrays
 
Odoo from 7.0 to 8.0 API
Odoo from 7.0 to 8.0 APIOdoo from 7.0 to 8.0 API
Odoo from 7.0 to 8.0 API
 
Odoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new api
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
displaytag
displaytagdisplaytag
displaytag
 
Data Types & Objects .pptx
Data Types & Objects .pptxData Types & Objects .pptx
Data Types & Objects .pptx
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talk
 
Elastic tire demo
Elastic tire demoElastic tire demo
Elastic tire demo
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data Objects
 
java ee 6 Petcatalog
java ee 6 Petcatalogjava ee 6 Petcatalog
java ee 6 Petcatalog
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with Django
 

Mehr von Hoang Nguyen

GANs and Applications
GANs and ApplicationsGANs and Applications
GANs and ApplicationsHoang Nguyen
 
Scrum - An introduction
Scrum - An introductionScrum - An introduction
Scrum - An introductionHoang Nguyen
 
Introduction to Cross-platform App Development
Introduction to Cross-platform App DevelopmentIntroduction to Cross-platform App Development
Introduction to Cross-platform App DevelopmentHoang Nguyen
 
Conistency of random forests
Conistency of random forestsConistency of random forests
Conistency of random forestsHoang Nguyen
 
Trust - Digital Signature
Trust - Digital SignatureTrust - Digital Signature
Trust - Digital SignatureHoang Nguyen
 
SOME SECURITY CHALLENGES IN CLOUD COMPUTING
SOME SECURITY CHALLENGES  IN CLOUD COMPUTINGSOME SECURITY CHALLENGES  IN CLOUD COMPUTING
SOME SECURITY CHALLENGES IN CLOUD COMPUTINGHoang Nguyen
 
Information, Data and Decision Making
Information, Data and Decision MakingInformation, Data and Decision Making
Information, Data and Decision MakingHoang Nguyen
 
Multiple processor systems
Multiple processor systemsMultiple processor systems
Multiple processor systemsHoang Nguyen
 
Multiprocessor Systems
Multiprocessor SystemsMultiprocessor Systems
Multiprocessor SystemsHoang Nguyen
 
Introduction to AOS course
Introduction to AOS courseIntroduction to AOS course
Introduction to AOS courseHoang Nguyen
 
Background Knowledge
Background KnowledgeBackground Knowledge
Background KnowledgeHoang Nguyen
 
Introduction to Information Security Course
Introduction to Information Security CourseIntroduction to Information Security Course
Introduction to Information Security CourseHoang Nguyen
 
Introduction to CNS Course
Introduction to CNS CourseIntroduction to CNS Course
Introduction to CNS CourseHoang Nguyen
 

Mehr von Hoang Nguyen (20)

GANs and Applications
GANs and ApplicationsGANs and Applications
GANs and Applications
 
Scrum - An introduction
Scrum - An introductionScrum - An introduction
Scrum - An introduction
 
Introduction to Cross-platform App Development
Introduction to Cross-platform App DevelopmentIntroduction to Cross-platform App Development
Introduction to Cross-platform App Development
 
Conistency of random forests
Conistency of random forestsConistency of random forests
Conistency of random forests
 
Trust - Digital Signature
Trust - Digital SignatureTrust - Digital Signature
Trust - Digital Signature
 
Key Exchange
Key ExchangeKey Exchange
Key Exchange
 
SOME SECURITY CHALLENGES IN CLOUD COMPUTING
SOME SECURITY CHALLENGES  IN CLOUD COMPUTINGSOME SECURITY CHALLENGES  IN CLOUD COMPUTING
SOME SECURITY CHALLENGES IN CLOUD COMPUTING
 
Stream ciphers
Stream ciphersStream ciphers
Stream ciphers
 
Classical ciphers
Classical ciphersClassical ciphers
Classical ciphers
 
Confidentiality
ConfidentialityConfidentiality
Confidentiality
 
Information, Data and Decision Making
Information, Data and Decision MakingInformation, Data and Decision Making
Information, Data and Decision Making
 
Multiple processor systems
Multiple processor systemsMultiple processor systems
Multiple processor systems
 
Multiprocessor Systems
Multiprocessor SystemsMultiprocessor Systems
Multiprocessor Systems
 
Introduction to AOS course
Introduction to AOS courseIntroduction to AOS course
Introduction to AOS course
 
Background Knowledge
Background KnowledgeBackground Knowledge
Background Knowledge
 
Introduction to Information Security Course
Introduction to Information Security CourseIntroduction to Information Security Course
Introduction to Information Security Course
 
Introduction to CNS Course
Introduction to CNS CourseIntroduction to CNS Course
Introduction to CNS Course
 
Dynamic Testing
Dynamic TestingDynamic Testing
Dynamic Testing
 
Nosql intro
Nosql introNosql intro
Nosql intro
 
Static Testing
Static TestingStatic Testing
Static Testing
 

Último

My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kitJamie (Taka) Wang
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for  Biomedical ApplicationsGraphene Quantum Dots-Based Composites for  Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applicationsnooralam814309
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdfThe Good Food Institute
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxKaustubhBhavsar6
 
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarEMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarThousandEyes
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingMAGNIntelligence
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4DianaGray10
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Libraryshyamraj55
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 

Último (20)

My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kit
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for  Biomedical ApplicationsGraphene Quantum Dots-Based Composites for  Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applications
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptx
 
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarEMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? Webinar
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced Computing
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 

ORM in Django

  • 2. [Agenda] ORM, What is? and learn by hand 
  • 3. [OOP, What does this mean?]
  • 4. [Welcome to of Objects]
  • 5. Each object is a Lego piece
  • 6. This Lego bear sculpture contains over 95,000 LEGO pieces and took over 1100 hours to construct together.
  • 7. This amazing Lego airport was showcased in LegoCity, at Senayan City, Indonesia.
  • 8. This machine has several playable features include functional powered treads for movement, full suspension and front and rear steering. A true masterpiece.
  • 9. Do you love Lego, too?
  • 10. if you are programmer { while (true) { YOU OOP! } }
  • 11. We also need persistence
  • 12. [How we do persistence] OOP languages provide object persistence But it is fragile Relational databases Can store vast amounts of data in a structured way that allows for efficient storage, access, and search NoSQL solutions truly vast datasets, real time and concurrent
  • 13. [so, What problem] Table Column RowClass Object Attrib- ute key – value pairRelationMethod Inher- itance Associ- ation
  • 14. public const string ConnectionString = @"Data Source=.Sqlexpress;Initial Catalog=Example;Integrated Security=SSPI;"; string sql = "select * from table where fname = '" + firstName + "' and lname = '" + lastName + "'"; using (SqlConnection connection = new SqlConnection(ConnectionString)){ using (SqlCommand command = new SqlCommand(sql, connection)) { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { string output = "First Name: {0} t Last Name: {1} t Phone: {2}"; Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]); } } }
  • 15. SELECT '%c%' as Chapter, (SELECT count(ticket.id) as Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status IN ('new','assigned') ) AS 'New', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='document_interface' ) AS 'Document Interface', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='interface_development' ) AS 'Interface Development', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='interface_check' ) AS 'Interface Check', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='document_routine' ) AS 'Document Routine', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='full_development' ) AS 'Full Development', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='peer_review_1' ) AS 'Peer Review One', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%‘ AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='peer_review_2' ) AS 'Peer Review Two', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='qa' ) AS 'QA', (SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%‘ AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine' AND ticket.status='closed' ) AS 'Closed', count(id) AS Total, ticket.id AS _id FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket WHERE ticket_custom.name='chapter' AND ticket_custom.value LIKE '%c%' AND type='New material' AND milestone='1.1.12' AND component NOT LIKE 'internal_engine'
  • 16. I am programmer. I love OOP. I hate SQL.
  • 17. You hear me. ORM is sexy.
  • 18. [ORM, What is] Object - Relational Mapping type systems object-oriented virtual object database bunch of code provides a set of APIs which allows access databases in OO style helps database become more transparent
  • 19. [ORM, What is] 1994: TopLink for SmallTalk – the first ORM 2001 – 2002: Hibernate Entity Framework and LINQ ACTIVE RECORD CORE DATA Gavin King
  • 21. ORM is the Vietnam of Computer Science http://blogs.tedneward.com/post/the-vietnam-of-computer-science/ https://blog.codinghorror.com/object-relational-mapping-is-the-vietnam-of-computer-science/ http://martinfowler.com/bliki/OrmHate.html
  • 22. Trying to match two different world
  • 23. How to work with ORM in Django
  • 24. [ORM in Django] Save for insert and update Delete for, well, delete And some methods to load records
  • 25. [How to create a model]
  • 26. Must inherit from the Model class Model class inside the models package (django.db.models.Model) Model add ORM methods, such as save() and delete() Model add an objects collection as a property for querying data Create Student Model [How to create a model]
  • 27. property_name = models.Type(fieldOptions) Type is some Field class inside models (you can create and use customize field classes) Each property_name exactly is an instance of some field class Each Field class represent a column type, which tells to the database what kind of data to store. fieldOptions is a set of field-specific arguments [How to create a model]
  • 28. [How to create string Field] property_name = models.CharField(fieldOptions) property_name = models.TextField(fieldOptions) max_length: integer number represent maximum number of characters null: bool value to indicate if null value is allowed. False by default. blank: bool value to indicate if empty string is allowed. False by default. default: default value if none is provided choices: enumeration
  • 29. [How to create number Field] property_name = models.BigIntegerField(fieldOptions) property_name = models.IntegerField(fieldOptions) property_name = models.SmallIntegerField(fieldOptions) property_name = models.PositiveIntegerField(fieldOptions) property_name = models.PositiveSmallIntegerField(fieldOptions) property_name = models.FloatField(fieldOptions) null: bool value to indicate if null value is allowed. False by default. default: default value if none is provided
  • 30. [How to create Boolean Field] property_name = models.BooleanField(fieldOptions) property_name = models.NullBooleanField(fieldOptions) null: bool value to indicate if null value is allowed. False by default. default: default value if none is provided
  • 31. [How to create date - time Field] property_name = models.DateField(fieldOptions) property_name = models.TimeField(fieldOptions) property_name = models.DateTimeField(fieldOptions) auto_now: automatically set the field to now every time the object is saved. False by default. Note that the current date is always used; it’s not just a default value that you can override. auto_now_add: automatically set the field to now when the object is first created. Note that the current date is always used; it’s not just a default value that you can override.
  • 32. [Some special fields] A CharField that checks that the value is a valid email address. max_length=254 A CharField that checks that the value is a valid url. max_length=200 A CharField that checks that the value is a valid IP address. protocol: both, IPv4, IPv6 unpack_ipv4: to convert a packed address(::ffff:192.0.2.1) to ipv4 address (192.0.2.1)
  • 33. [Some special fields] upload_to: the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. upload_to may also be a callable, such as a function All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You can get absolute path use mug_shot.url Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. height_field=None, width_field=None
  • 34. Read API reference for the other field types
  • 36. [How to create a primary key] Must be unique for each record Typically has a name of id Typically is a auto-generate number models.CharField(primary_key=True) models.IntField(primary_key=True) models.AutoField(primary_key=True)
  • 37. [Exercise 1] first_name: is a string, length <= 30, not null, not blank mid_name: is a string, length <= 50, nullable, blankable last_name: is a string, length <=30, not null, not blank birthday: for storing the date of birth admission_day: for storing the date and time gender: F or M class_name: is a string, length <= 50 special: is a string, length <=100 class_term: is a integer number
  • 39. [How to create relationships] ForeignKey ManyToManyField OneToOneField
  • 40. [How to connect to database]
  • 41. [How to connect to database] for details SQLite MySQL Oracle PostgreSQL
  • 42. [How to sync between models and database] Creates a package that contains all of the changes to be made on the database based on the code changes in the models --name Synchronizes the database state with the current set of models and migrations --fake Prints the SQL for the named migration
  • 43. [How to CRUD in OO style]
  • 44. [How to CRUD in OO style]
  • 45. [How to CRUD in OO style]
  • 47. lazy QuerySet has two public properties: ordered and db Two main kinds of functions return an instance of QuerySet class: all, filter, exclude, annotate, orderby, distinct, … get, count, first, last, Avg, Count, Max, Min, Sum, Variance, StdDev, … Example with get, all functions [How to Retrieve in OO style]
  • 48. [How to Retrieve in OO style] values(‘property1’, ‘property2’, …) to select some properties Lookup expression Django is aware of your object structure => we can query data using the class structure we created. Use two underscore to call function or deeper property String funcs: exact, contains, startswith, endswith, regex, Use i prefix to call insensitive string funcs Number funcs: gt, gte, lt, lte, range, … Use in for list and subquery statements Limiting QuerySet: [5], [:5], [5:10] Examples with get, filter and exclude
  • 49. [How to Retrieve in OO style] How to make complex lookup expression Chaining filters Student.objects.filter(first_name__exact=‘Nguyen’).filter(last_name__exact=‘Hoang’) Q() objects &, |, ~ Q(first_name__exact=‘Nguyen’) & Q(last_name__exact=‘Hoang’) Multiple update and delete filters.delete() filters.update(property1=value1, …) filters.update(property1 = F(‘property1’) + 1, property2 = F(‘property3’) + 2)
  • 50. “More like science. You grab this piece of library and you poke at it. You write programs that poke it and see what it does. And you say, ‘Can I tweak it to do the thing I want?’” As to why they chose Python as an alternative, Sussman joked that it was “late binding” decision. Python has a ton of libraries that make it applicable to many types of projects that instructors might want to assign (like writing software to control a robot.)