SlideShare uma empresa Scribd logo
1 de 50
Baixar para ler offline
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
[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.)

Mais conteúdo relacionado

Mais procurados

Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingHaim Michael
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
React state
React  stateReact  state
React stateDucat
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSHoang Long
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
Introduction to JSX
Introduction to JSXIntroduction to JSX
Introduction to JSXMicah Wood
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 

Mais procurados (20)

Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
JQuery UI
JQuery UIJQuery UI
JQuery UI
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
React state
React  stateReact  state
React state
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Linq
LinqLinq
Linq
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Introduction to JSX
Introduction to JSXIntroduction to JSX
Introduction to JSX
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 

Destaque

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.
 

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

Semelhante a ORM in Django

So basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfSo basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfeyewaregallery
 
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
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Andrey Volobuev
 
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
 
public static void main(String[], args) throws FileNotFoundExcepti.pdf
public static void main(String[], args) throws FileNotFoundExcepti.pdfpublic static void main(String[], args) throws FileNotFoundExcepti.pdf
public static void main(String[], args) throws FileNotFoundExcepti.pdffms12345
 

Semelhante a ORM in Django (20)

So basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfSo basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdf
 
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
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)
 
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
 
public static void main(String[], args) throws FileNotFoundExcepti.pdf
public static void main(String[], args) throws FileNotFoundExcepti.pdfpublic static void main(String[], args) throws FileNotFoundExcepti.pdf
public static void main(String[], args) throws FileNotFoundExcepti.pdf
 

Mais de 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
 

Mais de 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

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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
  • 35.
  • 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.)