SlideShare a Scribd company logo
1 of 21
Simple Django
Models
Charles Severance
www.dj4e.com
Linux
Browser
Django
WGSIConfig
Routing
Views
Database
Templates
settings.py
N
G
I
N
X
urls.py
views.py
forms.py
Models
models.py
D
O
M
Parse
Response
Javascript admin.py
Shell
/admin
SQL
Structured Query Language is the
language we use to issue
commands to the database
- Create/Insert data
- Read/Select some data
- Update data
- Delete data
http://en.wikipedia.org/wiki/SQL
https://en.wikipedia.org/wiki/ANSI-
SPARC_Architecture
Start Simple - A
Single Table
CREATE TABLE Users(
id integer NOT NULL
PRIMARY KEY
AUTOINCREMENT,
name VARCHAR(128),
email VARCHAR(128)
);
$ sqlite3 zip.sqlite3
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
sqlite> .tables
sqlite> CREATE TABLE Users(
...> id INTEGER NOT NULL
...> PRIMARY KEY AUTOINCREMENT,
...> name VARCHAR(128),
...> email VARCHAR(128)
...> ) ;
sqlite> .tables
Users
sqlite> .schema Users
CREATE TABLE Users(
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR(128),
email VARCHAR(128)
);
sqlite> https://www.dj4e.com/lectures/SQL-01-Basics.txt
SQL Summary
SELECT * FROM Users
SELECT * FROM Users WHERE email='csev@umich.edu'
UPDATE Users SET name="Charles" WHERE email='csev@umich.edu'
INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu')
DELETE FROM Users WHERE email='ted@umich.edu'
SELECT * FROM Users ORDER BY email
Object Relational Mapping (ORM)
• Allows us to map tables to objects and columns
• We use those objects to store and retrieve data from the database
• Improved portability across database dialects (SQLite, MySQL,
Postgres, Oracle)
Python Model
library
models.py
SQLite
SQL
Postgres
MySQL
Defining a table SQL:
CREATE TABLE Users(
name VARCHAR(128),
email VARCHAR(128)
);
models.py:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=128)
email = models.CharField(max_length=128)
https://github.com/csev/dj4e-samples/tree/master/users
https://github.com/csev/dj4e-samples/tree/master/users
$ cd ~/dj4e-samples
$ python3 manage.py makemigrations
Migrations for 'users':
users/migrations/0001_initial.py
- Create model User
$ python3 manage.py migrate
Running migrations:
Applying contenttypes.0001_initial... OK
...
Applying sessions.0001_initial... OK
Applying users.0001_initial... OK
models.py:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=128)
email = models.CharField(max_length=128)
Creating the Table
from the Model
https://github.com/csev/dj4e-samples/tree/master/users
$ cd ~/dj4e-samples
$ sqlite3 db.sqlite3
SQLite version 3.24.0 2018-06-04 14:10:15
Enter ".help" for usage hints.
sqlite> .tables
auth_group django_admin_log
[ ..snip ..]
auth_user django_session
auth_user_groups users_user
auth_user_user_permissions
sqlite> .schema users_user
CREATE TABLE IF NOT EXISTS "users_user" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" varchar(128) NOT NULL,
"email" varchar(128) NOT NULL
);
sqlite> .quit
Checking…
Inserting a Record
INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu')
https://github.com/csev/dj4e-samples/tree/master/users
$ cd ~/dj4e-samples
$ python3 manage.py shell
>>> from users.models import User
>>> u = User(name='Kristen', email='kf@umich.edu')
>>> u.save()
>>> print(u.id)
1
>>> print(u.email)
kf@umich.edu
>>>
Checking…
>>> from django.db import connection
>>> print(connection.queries)
[
{'sql': 'BEGIN', 'time': '0.000'},
{'sql': 'INSERT INTO "users_user" ("name", "email")
VALUES ('Kristen', 'kf@umich.edu')',
'time': '0.002'}
]
>>>
https://github.com/csev/dj4e-samples/tree/master/users
INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu')
CRUD in the ORM
u = User(name='Sally', email='a2@umich.edu')
u.save()
User.objects.values()
User.objects.filter(email='csev@umich.edu').values()
User.objects.filter(email='ted@umich.edu').delete()
User.objects.values()
User.objects.filter(email='csev@umich.edu').update(name='Charles')
User.objects.values()
User.objects.values().order_by('email')
User.objects.values().order_by('-name')
Model Field Types
• AutoField
• BigAutoField
• BigIntegerField
• BinaryField
• BooleanField
• CharField
• DateField
• DateTimeField
• DecimalField
• DurationField
• EmailField
• FileField
• FilePathField
• FloatField
• ImageField
• IntegerField
• GenericIPAddressField
• NullBooleanField
• PositiveIntegerField
https://docs.djangoproject.com/en/4.2/ref/models/fields/#field-types
• PositiveSmallIntegerField
• SlugField
• SmallIntegerField
• TextFIeld
• TimeField
• URLField
• ForeignKey
• ManyToManyField
• OneToOneField
Models, Migrations, and
Database Tables
Migrations: From Model to Database
• The makemigrations command reads all the models.py files in all the
applications, end creates / evolves the migration files
• Guided by the applications listed in settings.py
• Migrations are portable across databases
• The migrate command reads all the migrations folders in the
application folders and creates / evolves the tables in the database
(i.e. db.sqlite3)
makemigrations
dj4e-samples$ ls */migrations/0*.py
autos/migrations/0001_initial.py
bookmany/migrations/0001_initial.py
bookone/migrations/0001_initial.py
favs/migrations/0001_initial.py
favsql/migrations/0001_initial.py
forums/migrations/0001_initial.py
gview/migrations/0001_initial.py
many/migrations/0001_initial.py
myarts/migrations/0001_initial.py
pics/migrations/0001_initial.py
rest/migrations/0001_initial.py
tracks/migrations/0001_initial.py
users/migrations/0001_initial.py
dj4e-samples$
dj4e-samples$ ls */models.py
autos/models.py many/models.py
bookone/models.py menu/models.py
crispy/models.py myarts/models.py
favs/models.py pics/models.py
favsql/models.py rest/models.py
form/models.py route/models.py
forums/models.py session/models.py
getpost/models.py tmpl/models.py
gview/models.py tracks/models.py
hello/models.py users/models.py
home/models.py views/models.py
dj4e-samples$
migrate dj4e-samples$ sqlite3 db.sqlite3
SQLite version 3.24.0 2018-06-04 14:10:15
Enter ".help" for usage hints.
sqlite> .tables
auth_group gview_car
auth_group_permissions gview_cat
auth_permission gview_dog
auth_user gview_horse
auth_user_groups many_course
auth_user_user_permissions many_membership
autos_auto many_person
autos_make myarts_article
bookone_book pics_pic
bookone_instance rest_breed
bookone_lang rest_cat
django_admin_log social_auth_association
django_content_type social_auth_code
django_migrations social_auth_nonce
django_session social_auth_partial
favs_fav social_auth_usersocialauth
favs_thing tracks_album
favsql_fav tracks_artist
favsql_thing tracks_genre
forums_comment tracks_track
forums_forum users_user
sqlite> .quit
dj4e-samples$
dj4e-samples$ ls */migrations/0*.py
autos/migrations/0001_initial.py
bookmany/migrations/0001_initial.py
bookone/migrations/0001_initial.py
favs/migrations/0001_initial.py
favsql/migrations/0001_initial.py
forums/migrations/0001_initial.py
gview/migrations/0001_initial.py
many/migrations/0001_initial.py
myarts/migrations/0001_initial.py
pics/migrations/0001_initial.py
rest/migrations/0001_initial.py
tracks/migrations/0001_initial.py
users/migrations/0001_initial.py
dj4e-samples$
Re-running makemigrate
dj4e-samples$ rm bookone/migrations/0001_initial.py
MacBook-Pro-92:dj4e-samples csev$ python3 manage.py makemigrations
Migrations for 'bookone':
bookone/migrations/0001_initial.py
- Create model Book
- Create model Instance
- Create model Lang
- Add field lang to book
dj4e-samples$
Re-running migrate from scratch
dj4e-samples$ rm db.sqlite3
dj4e-samples$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, autos, bookone, contenttypes, ...
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
[ ...snip ... ]
Applying social_django.0008_partial_timestamp... OK
Applying tracks.0001_initial... OK
Applying users.0001_initial... OK
dj4e-samples$
Summary
• The Django Models feature implements an Object Relational Mapper
• Benefits
• We can write only Python code (i.e. no explicit SQL)
• We gain database portability
• Migrations both create and evolve our database schema
• A sweet administrator interface
• Automatic form generation and validation (later)
Acknowledgements / Contributions
These slides are Copyright 2019- Charles R. Severance
(www.dr-chuck.com) as part of www.dj4e.com and made
available under a Creative Commons Attribution 4.0 License.
Please maintain this last slide in all copies of the document to
comply with the attribution requirements of the license. If you
make a change, feel free to add your name and organization to
the list of contributors on this page as you republish the
materials.
Initial Development: Charles Severance, University of Michigan
School of Information
Insert new Contributors and Translators here including names
and dates
Continue new Contributors and Translators here

More Related Content

Similar to DJ-02-Model-Single.pptx

Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)andrewnacin
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)Ehtisham Ali
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web DevelopmentCheng-Yi Yu
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHPDave Ross
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And AnishOSSCube
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019Ayesh Karunaratne
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyBalázs Tatár
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinTobias Zander
 

Similar to DJ-02-Model-Single.pptx (20)

Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
Php summary
Php summaryPhp summary
Php summary
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web Development
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
Django
DjangoDjango
Django
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in Berlin
 

Recently uploaded

SCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarj
SCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarjSCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarj
SCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarjadimosmejiaslendon
 
edited gordis ebook sixth edition david d.pdf
edited gordis ebook sixth edition david d.pdfedited gordis ebook sixth edition david d.pdf
edited gordis ebook sixth edition david d.pdfgreat91
 
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...Klinik Aborsi
 
Bios of leading Astrologers & Researchers
Bios of leading Astrologers & ResearchersBios of leading Astrologers & Researchers
Bios of leading Astrologers & Researchersdarmandersingh4580
 
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证acoha1
 
Formulas dax para power bI de microsoft.pdf
Formulas dax para power bI de microsoft.pdfFormulas dax para power bI de microsoft.pdf
Formulas dax para power bI de microsoft.pdfRobertoOcampo24
 
Credit Card Fraud Detection: Safeguarding Transactions in the Digital Age
Credit Card Fraud Detection: Safeguarding Transactions in the Digital AgeCredit Card Fraud Detection: Safeguarding Transactions in the Digital Age
Credit Card Fraud Detection: Safeguarding Transactions in the Digital AgeBoston Institute of Analytics
 
如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证
如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证
如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证zifhagzkk
 
The Significance of Transliteration Enhancing
The Significance of Transliteration EnhancingThe Significance of Transliteration Enhancing
The Significance of Transliteration Enhancingmohamed Elzalabany
 
原件一样伦敦国王学院毕业证成绩单留信学历认证
原件一样伦敦国王学院毕业证成绩单留信学历认证原件一样伦敦国王学院毕业证成绩单留信学历认证
原件一样伦敦国王学院毕业证成绩单留信学历认证pwgnohujw
 
一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单
一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单
一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单aqpto5bt
 
Seven tools of quality control.slideshare
Seven tools of quality control.slideshareSeven tools of quality control.slideshare
Seven tools of quality control.slideshareraiaryan448
 
Displacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second DerivativesDisplacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second Derivatives23050636
 
How to Transform Clinical Trial Management with Advanced Data Analytics
How to Transform Clinical Trial Management with Advanced Data AnalyticsHow to Transform Clinical Trial Management with Advanced Data Analytics
How to Transform Clinical Trial Management with Advanced Data AnalyticsBrainSell Technologies
 
NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...
NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...
NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...Amil baba
 
Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024patrickdtherriault
 
obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...
obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...
obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...yulianti213969
 
Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...
Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...
Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...ssuserf63bd7
 
Go paperless and transform your procurement process with the Hive Collaborati...
Go paperless and transform your procurement process with the Hive Collaborati...Go paperless and transform your procurement process with the Hive Collaborati...
Go paperless and transform your procurement process with the Hive Collaborati...LitoGarin1
 
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样jk0tkvfv
 

Recently uploaded (20)

SCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarj
SCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarjSCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarj
SCI8-Q4-MOD11.pdfwrwujrrjfaajerjrajrrarj
 
edited gordis ebook sixth edition david d.pdf
edited gordis ebook sixth edition david d.pdfedited gordis ebook sixth edition david d.pdf
edited gordis ebook sixth edition david d.pdf
 
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
 
Bios of leading Astrologers & Researchers
Bios of leading Astrologers & ResearchersBios of leading Astrologers & Researchers
Bios of leading Astrologers & Researchers
 
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
 
Formulas dax para power bI de microsoft.pdf
Formulas dax para power bI de microsoft.pdfFormulas dax para power bI de microsoft.pdf
Formulas dax para power bI de microsoft.pdf
 
Credit Card Fraud Detection: Safeguarding Transactions in the Digital Age
Credit Card Fraud Detection: Safeguarding Transactions in the Digital AgeCredit Card Fraud Detection: Safeguarding Transactions in the Digital Age
Credit Card Fraud Detection: Safeguarding Transactions in the Digital Age
 
如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证
如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证
如何办理(Dalhousie毕业证书)达尔豪斯大学毕业证成绩单留信学历认证
 
The Significance of Transliteration Enhancing
The Significance of Transliteration EnhancingThe Significance of Transliteration Enhancing
The Significance of Transliteration Enhancing
 
原件一样伦敦国王学院毕业证成绩单留信学历认证
原件一样伦敦国王学院毕业证成绩单留信学历认证原件一样伦敦国王学院毕业证成绩单留信学历认证
原件一样伦敦国王学院毕业证成绩单留信学历认证
 
一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单
一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单
一比一原版(ucla文凭证书)加州大学洛杉矶分校毕业证学历认证官方成绩单
 
Seven tools of quality control.slideshare
Seven tools of quality control.slideshareSeven tools of quality control.slideshare
Seven tools of quality control.slideshare
 
Displacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second DerivativesDisplacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second Derivatives
 
How to Transform Clinical Trial Management with Advanced Data Analytics
How to Transform Clinical Trial Management with Advanced Data AnalyticsHow to Transform Clinical Trial Management with Advanced Data Analytics
How to Transform Clinical Trial Management with Advanced Data Analytics
 
NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...
NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...
NO1 Best Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialist I...
 
Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024
 
obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...
obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...
obat aborsi Bontang wa 081336238223 jual obat aborsi cytotec asli di Bontang6...
 
Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...
Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...
Statistics Informed Decisions Using Data 5th edition by Michael Sullivan solu...
 
Go paperless and transform your procurement process with the Hive Collaborati...
Go paperless and transform your procurement process with the Hive Collaborati...Go paperless and transform your procurement process with the Hive Collaborati...
Go paperless and transform your procurement process with the Hive Collaborati...
 
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样
如何办理(UCLA毕业证书)加州大学洛杉矶分校毕业证成绩单学位证留信学历认证原件一样
 

DJ-02-Model-Single.pptx

  • 3. SQL Structured Query Language is the language we use to issue commands to the database - Create/Insert data - Read/Select some data - Update data - Delete data http://en.wikipedia.org/wiki/SQL https://en.wikipedia.org/wiki/ANSI- SPARC_Architecture
  • 4. Start Simple - A Single Table CREATE TABLE Users( id integer NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(128), email VARCHAR(128) ); $ sqlite3 zip.sqlite3 SQLite version 3.11.0 2016-02-15 17:29:24 Enter ".help" for usage hints. sqlite> .tables sqlite> CREATE TABLE Users( ...> id INTEGER NOT NULL ...> PRIMARY KEY AUTOINCREMENT, ...> name VARCHAR(128), ...> email VARCHAR(128) ...> ) ; sqlite> .tables Users sqlite> .schema Users CREATE TABLE Users( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(128), email VARCHAR(128) ); sqlite> https://www.dj4e.com/lectures/SQL-01-Basics.txt
  • 5. SQL Summary SELECT * FROM Users SELECT * FROM Users WHERE email='csev@umich.edu' UPDATE Users SET name="Charles" WHERE email='csev@umich.edu' INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu') DELETE FROM Users WHERE email='ted@umich.edu' SELECT * FROM Users ORDER BY email
  • 6. Object Relational Mapping (ORM) • Allows us to map tables to objects and columns • We use those objects to store and retrieve data from the database • Improved portability across database dialects (SQLite, MySQL, Postgres, Oracle) Python Model library models.py SQLite SQL Postgres MySQL
  • 7. Defining a table SQL: CREATE TABLE Users( name VARCHAR(128), email VARCHAR(128) ); models.py: from django.db import models class User(models.Model): name = models.CharField(max_length=128) email = models.CharField(max_length=128) https://github.com/csev/dj4e-samples/tree/master/users
  • 8. https://github.com/csev/dj4e-samples/tree/master/users $ cd ~/dj4e-samples $ python3 manage.py makemigrations Migrations for 'users': users/migrations/0001_initial.py - Create model User $ python3 manage.py migrate Running migrations: Applying contenttypes.0001_initial... OK ... Applying sessions.0001_initial... OK Applying users.0001_initial... OK models.py: from django.db import models class User(models.Model): name = models.CharField(max_length=128) email = models.CharField(max_length=128) Creating the Table from the Model
  • 9. https://github.com/csev/dj4e-samples/tree/master/users $ cd ~/dj4e-samples $ sqlite3 db.sqlite3 SQLite version 3.24.0 2018-06-04 14:10:15 Enter ".help" for usage hints. sqlite> .tables auth_group django_admin_log [ ..snip ..] auth_user django_session auth_user_groups users_user auth_user_user_permissions sqlite> .schema users_user CREATE TABLE IF NOT EXISTS "users_user" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(128) NOT NULL, "email" varchar(128) NOT NULL ); sqlite> .quit Checking…
  • 10. Inserting a Record INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu') https://github.com/csev/dj4e-samples/tree/master/users $ cd ~/dj4e-samples $ python3 manage.py shell >>> from users.models import User >>> u = User(name='Kristen', email='kf@umich.edu') >>> u.save() >>> print(u.id) 1 >>> print(u.email) kf@umich.edu >>>
  • 11. Checking… >>> from django.db import connection >>> print(connection.queries) [ {'sql': 'BEGIN', 'time': '0.000'}, {'sql': 'INSERT INTO "users_user" ("name", "email") VALUES ('Kristen', 'kf@umich.edu')', 'time': '0.002'} ] >>> https://github.com/csev/dj4e-samples/tree/master/users INSERT INTO Users (name, email) VALUES ('Kristin', 'kf@umich.edu')
  • 12. CRUD in the ORM u = User(name='Sally', email='a2@umich.edu') u.save() User.objects.values() User.objects.filter(email='csev@umich.edu').values() User.objects.filter(email='ted@umich.edu').delete() User.objects.values() User.objects.filter(email='csev@umich.edu').update(name='Charles') User.objects.values() User.objects.values().order_by('email') User.objects.values().order_by('-name')
  • 13. Model Field Types • AutoField • BigAutoField • BigIntegerField • BinaryField • BooleanField • CharField • DateField • DateTimeField • DecimalField • DurationField • EmailField • FileField • FilePathField • FloatField • ImageField • IntegerField • GenericIPAddressField • NullBooleanField • PositiveIntegerField https://docs.djangoproject.com/en/4.2/ref/models/fields/#field-types • PositiveSmallIntegerField • SlugField • SmallIntegerField • TextFIeld • TimeField • URLField • ForeignKey • ManyToManyField • OneToOneField
  • 15. Migrations: From Model to Database • The makemigrations command reads all the models.py files in all the applications, end creates / evolves the migration files • Guided by the applications listed in settings.py • Migrations are portable across databases • The migrate command reads all the migrations folders in the application folders and creates / evolves the tables in the database (i.e. db.sqlite3)
  • 16. makemigrations dj4e-samples$ ls */migrations/0*.py autos/migrations/0001_initial.py bookmany/migrations/0001_initial.py bookone/migrations/0001_initial.py favs/migrations/0001_initial.py favsql/migrations/0001_initial.py forums/migrations/0001_initial.py gview/migrations/0001_initial.py many/migrations/0001_initial.py myarts/migrations/0001_initial.py pics/migrations/0001_initial.py rest/migrations/0001_initial.py tracks/migrations/0001_initial.py users/migrations/0001_initial.py dj4e-samples$ dj4e-samples$ ls */models.py autos/models.py many/models.py bookone/models.py menu/models.py crispy/models.py myarts/models.py favs/models.py pics/models.py favsql/models.py rest/models.py form/models.py route/models.py forums/models.py session/models.py getpost/models.py tmpl/models.py gview/models.py tracks/models.py hello/models.py users/models.py home/models.py views/models.py dj4e-samples$
  • 17. migrate dj4e-samples$ sqlite3 db.sqlite3 SQLite version 3.24.0 2018-06-04 14:10:15 Enter ".help" for usage hints. sqlite> .tables auth_group gview_car auth_group_permissions gview_cat auth_permission gview_dog auth_user gview_horse auth_user_groups many_course auth_user_user_permissions many_membership autos_auto many_person autos_make myarts_article bookone_book pics_pic bookone_instance rest_breed bookone_lang rest_cat django_admin_log social_auth_association django_content_type social_auth_code django_migrations social_auth_nonce django_session social_auth_partial favs_fav social_auth_usersocialauth favs_thing tracks_album favsql_fav tracks_artist favsql_thing tracks_genre forums_comment tracks_track forums_forum users_user sqlite> .quit dj4e-samples$ dj4e-samples$ ls */migrations/0*.py autos/migrations/0001_initial.py bookmany/migrations/0001_initial.py bookone/migrations/0001_initial.py favs/migrations/0001_initial.py favsql/migrations/0001_initial.py forums/migrations/0001_initial.py gview/migrations/0001_initial.py many/migrations/0001_initial.py myarts/migrations/0001_initial.py pics/migrations/0001_initial.py rest/migrations/0001_initial.py tracks/migrations/0001_initial.py users/migrations/0001_initial.py dj4e-samples$
  • 18. Re-running makemigrate dj4e-samples$ rm bookone/migrations/0001_initial.py MacBook-Pro-92:dj4e-samples csev$ python3 manage.py makemigrations Migrations for 'bookone': bookone/migrations/0001_initial.py - Create model Book - Create model Instance - Create model Lang - Add field lang to book dj4e-samples$
  • 19. Re-running migrate from scratch dj4e-samples$ rm db.sqlite3 dj4e-samples$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, autos, bookone, contenttypes, ... Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK [ ...snip ... ] Applying social_django.0008_partial_timestamp... OK Applying tracks.0001_initial... OK Applying users.0001_initial... OK dj4e-samples$
  • 20. Summary • The Django Models feature implements an Object Relational Mapper • Benefits • We can write only Python code (i.e. no explicit SQL) • We gain database portability • Migrations both create and evolve our database schema • A sweet administrator interface • Automatic form generation and validation (later)
  • 21. Acknowledgements / Contributions These slides are Copyright 2019- Charles R. Severance (www.dr-chuck.com) as part of www.dj4e.com and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Continue new Contributors and Translators here