The document discusses Object Relational Mapping (ORM) in Django. It begins by explaining that ORM provides an API that allows accessing databases in an object-oriented style, making the database more transparent. It then provides examples of how to define models by inheriting from Django's Model class and adding fields. Various field types like CharField, IntegerField, DateField are demonstrated. It also shows how to define relationships and primary keys. The document concludes by explaining how to perform CRUD operations on models in an object-oriented way using Django's ORM APIs.
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.
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'
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
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
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
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
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.)