orm in django

50
ORM in DJANGO Hoang Nguyen

Upload: hoang-nguyen

Post on 27-Jan-2017

309 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: ORM in Django

ORM in DJANGOHoang Nguyen

Page 2: ORM in Django

[Agenda]ORM, What is?

and learn by hand

Page 3: ORM in Django

[OOP, What does this mean?]

Page 4: ORM in Django

[Welcome to of Objects]

Page 5: ORM in Django

Each object is a Lego piece

Page 6: ORM in Django

This Lego bear sculpture contains over 95,000 LEGO pieces and took over 1100 hours to construct together.

Page 7: ORM in Django

This amazing Lego airport was showcased in LegoCity, at Senayan City, Indonesia.

Page 8: ORM in Django

This machine has several playable features include functional powered treads for movement, full suspension and front and rear steering. A true masterpiece.

Page 9: ORM in Django

Do you love Lego, too?

Page 10: ORM in Django

if you are programmer {while (true) {

YOU OOP!}

}

Page 11: ORM in Django

We also need persistence

Page 12: ORM in Django

[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

Page 13: ORM in Django

[so, What problem]

Table Column RowClass Object Attrib-ute

key – valuepairRelationMethod Inher-

itance

Associ-ation

Page 14: ORM in Django

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"]);

}

}

}

Page 15: ORM in Django

SELECT '%c%' as Chapter,(SELECT count(ticket.id) as Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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.ticketWHERE 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' ANDticket.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.ticketWHERE 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' ANDticket.status='interface_development' ) AS 'Inter\face Development',(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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' ANDticket.status='interface_check' ) AS 'Interface C\heck',(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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' ANDticket.status='document_routine' ) AS 'Document R\outine',(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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' ANDticket.status='full_development' ) AS 'Full Devel\opment',(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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' ANDticket.status='peer_review_1' ) AS 'Peer Review O\ne',(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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' ANDticket.status='peer_review_2' ) AS 'Peer Review Tw\o',(SELECT count(ticket.id) AS Matches FROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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.ticketWHERE 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' ANDticket.status='closed' ) AS 'Closed',count(id) AS Total, ticket.id AS _idFROM engine.ticket INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticketWHERE 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'

Page 16: ORM in Django

I am programmer. I love OOP. I hate SQL.

Page 17: ORM in Django

You hear me. ORM is sexy.

Page 18: ORM in Django

[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

Page 19: ORM in Django

[ORM, What is]

1994: TopLink for SmallTalk – the first ORM

2001 – 2002: Hibernate

Entity Framework and LINQ

ACTIVE RECORD CORE DATA

Gavin King

Page 20: ORM in Django

[Discussion]

Page 21: ORM in Django

ORM is the Vietnam of Computer Sciencehttp://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

Page 22: ORM in Django

Trying to match two different world

Page 23: ORM in Django

How to work with ORM in Django

Page 24: ORM in Django

[ORM in Django]

Save for insert and update

Delete for, well, delete

And some methods to load records

Page 25: ORM in Django

[How to create a model]

Page 26: ORM in Django

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]

Page 27: ORM in Django

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]

Page 28: ORM in Django

[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

Page 29: ORM in Django

[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

Page 30: ORM in Django

[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

Page 31: ORM in Django

[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.

Page 32: ORM in Django

[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)

Page 33: ORM in Django

[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

Page 34: ORM in Django

Read API reference for the other field types

Page 35: ORM in Django
Page 36: 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)

Page 37: ORM in Django

[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

Page 38: ORM in Django

How about relationships?

Page 40: ORM in Django

[How to connect to database]

Page 41: ORM in Django

[How to connect to database] for details

SQLite

MySQL

Oracle

PostgreSQL

Page 42: ORM in Django

[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

Page 43: ORM in Django

[How to CRUD in OO style]

Page 44: ORM in Django

[How to CRUD in OO style]

Page 45: ORM in Django

[How to CRUD in OO style]

Page 46: ORM in Django

objects

objects

objects

objects

[How to Retrieve in OO style]

Page 47: ORM in Django

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]

Page 48: ORM in Django

[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

Page 49: ORM in Django

[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)

Page 50: ORM in Django

“More like science. You grab this piece of library and you poke at it. You writeprograms that poke it and see what it does. And you say, ‘Can I tweak it to do thething I want?’”

As to why they chose Python as an alternative, Sussman joked that it was “latebinding” decision. Python has a ton of libraries that make it applicable to manytypes of projects that instructors might want to assign (like writing software tocontrol a robot.)