SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

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
 
AI Imagen for data-storytelling Infographics.pdf
AI Imagen for data-storytelling Infographics.pdfAI Imagen for data-storytelling Infographics.pdf
AI Imagen for data-storytelling Infographics.pdfMichaelSenkow
 
一比一原版阿德莱德大学毕业证成绩单如何办理
一比一原版阿德莱德大学毕业证成绩单如何办理一比一原版阿德莱德大学毕业证成绩单如何办理
一比一原版阿德莱德大学毕业证成绩单如何办理pyhepag
 
2024 Q1 Tableau User Group Leader Quarterly Call
2024 Q1 Tableau User Group Leader Quarterly Call2024 Q1 Tableau User Group Leader Quarterly Call
2024 Q1 Tableau User Group Leader Quarterly Calllward7
 
basics of data science with application areas.pdf
basics of data science with application areas.pdfbasics of data science with application areas.pdf
basics of data science with application areas.pdfvyankatesh1
 
Easy and simple project file on mp online
Easy and simple project file on mp onlineEasy and simple project file on mp online
Easy and simple project file on mp onlinebalibahu1313
 
Pre-ProductionImproveddsfjgndflghtgg.pptx
Pre-ProductionImproveddsfjgndflghtgg.pptxPre-ProductionImproveddsfjgndflghtgg.pptx
Pre-ProductionImproveddsfjgndflghtgg.pptxStephen266013
 
Generative AI for Trailblazers_ Unlock the Future of AI.pdf
Generative AI for Trailblazers_ Unlock the Future of AI.pdfGenerative AI for Trailblazers_ Unlock the Future of AI.pdf
Generative AI for Trailblazers_ Unlock the Future of AI.pdfEmmanuel Dauda
 
Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...
Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...
Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...ssuserf63bd7
 
Exploratory Data Analysis - Dilip S.pptx
Exploratory Data Analysis - Dilip S.pptxExploratory Data Analysis - Dilip S.pptx
Exploratory Data Analysis - Dilip S.pptxDilipVasan
 
一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理
一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理
一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理pyhepag
 
一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理
一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理
一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理pyhepag
 
Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...
Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...
Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...Valters Lauzums
 
The Significance of Transliteration Enhancing
The Significance of Transliteration EnhancingThe Significance of Transliteration Enhancing
The Significance of Transliteration Enhancingmohamed Elzalabany
 
Supply chain analytics to combat the effects of Ukraine-Russia-conflict
Supply chain analytics to combat the effects of Ukraine-Russia-conflictSupply chain analytics to combat the effects of Ukraine-Russia-conflict
Supply chain analytics to combat the effects of Ukraine-Russia-conflictJack Cole
 
Fuzzy Sets decision making under information of uncertainty
Fuzzy Sets decision making under information of uncertaintyFuzzy Sets decision making under information of uncertainty
Fuzzy Sets decision making under information of uncertaintyRafigAliyev2
 
Artificial_General_Intelligence__storm_gen_article.pdf
Artificial_General_Intelligence__storm_gen_article.pdfArtificial_General_Intelligence__storm_gen_article.pdf
Artificial_General_Intelligence__storm_gen_article.pdfscitechtalktv
 
How I opened a fake bank account and didn't go to prison
How I opened a fake bank account and didn't go to prisonHow I opened a fake bank account and didn't go to prison
How I opened a fake bank account and didn't go to prisonPayment Village
 
一比一原版西悉尼大学毕业证成绩单如何办理
一比一原版西悉尼大学毕业证成绩单如何办理一比一原版西悉尼大学毕业证成绩单如何办理
一比一原版西悉尼大学毕业证成绩单如何办理pyhepag
 

Kürzlich hochgeladen (20)

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...
 
AI Imagen for data-storytelling Infographics.pdf
AI Imagen for data-storytelling Infographics.pdfAI Imagen for data-storytelling Infographics.pdf
AI Imagen for data-storytelling Infographics.pdf
 
一比一原版阿德莱德大学毕业证成绩单如何办理
一比一原版阿德莱德大学毕业证成绩单如何办理一比一原版阿德莱德大学毕业证成绩单如何办理
一比一原版阿德莱德大学毕业证成绩单如何办理
 
2024 Q1 Tableau User Group Leader Quarterly Call
2024 Q1 Tableau User Group Leader Quarterly Call2024 Q1 Tableau User Group Leader Quarterly Call
2024 Q1 Tableau User Group Leader Quarterly Call
 
basics of data science with application areas.pdf
basics of data science with application areas.pdfbasics of data science with application areas.pdf
basics of data science with application areas.pdf
 
Easy and simple project file on mp online
Easy and simple project file on mp onlineEasy and simple project file on mp online
Easy and simple project file on mp online
 
Pre-ProductionImproveddsfjgndflghtgg.pptx
Pre-ProductionImproveddsfjgndflghtgg.pptxPre-ProductionImproveddsfjgndflghtgg.pptx
Pre-ProductionImproveddsfjgndflghtgg.pptx
 
Generative AI for Trailblazers_ Unlock the Future of AI.pdf
Generative AI for Trailblazers_ Unlock the Future of AI.pdfGenerative AI for Trailblazers_ Unlock the Future of AI.pdf
Generative AI for Trailblazers_ Unlock the Future of AI.pdf
 
Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...
Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...
Data Visualization Exploring and Explaining with Data 1st Edition by Camm sol...
 
Exploratory Data Analysis - Dilip S.pptx
Exploratory Data Analysis - Dilip S.pptxExploratory Data Analysis - Dilip S.pptx
Exploratory Data Analysis - Dilip S.pptx
 
一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理
一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理
一比一原版加利福尼亚大学尔湾分校毕业证成绩单如何办理
 
一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理
一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理
一比一原版(Monash毕业证书)莫纳什大学毕业证成绩单如何办理
 
Machine Learning for Accident Severity Prediction
Machine Learning for Accident Severity PredictionMachine Learning for Accident Severity Prediction
Machine Learning for Accident Severity Prediction
 
Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...
Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...
Data Analytics for Digital Marketing Lecture for Advanced Digital & Social Me...
 
The Significance of Transliteration Enhancing
The Significance of Transliteration EnhancingThe Significance of Transliteration Enhancing
The Significance of Transliteration Enhancing
 
Supply chain analytics to combat the effects of Ukraine-Russia-conflict
Supply chain analytics to combat the effects of Ukraine-Russia-conflictSupply chain analytics to combat the effects of Ukraine-Russia-conflict
Supply chain analytics to combat the effects of Ukraine-Russia-conflict
 
Fuzzy Sets decision making under information of uncertainty
Fuzzy Sets decision making under information of uncertaintyFuzzy Sets decision making under information of uncertainty
Fuzzy Sets decision making under information of uncertainty
 
Artificial_General_Intelligence__storm_gen_article.pdf
Artificial_General_Intelligence__storm_gen_article.pdfArtificial_General_Intelligence__storm_gen_article.pdf
Artificial_General_Intelligence__storm_gen_article.pdf
 
How I opened a fake bank account and didn't go to prison
How I opened a fake bank account and didn't go to prisonHow I opened a fake bank account and didn't go to prison
How I opened a fake bank account and didn't go to prison
 
一比一原版西悉尼大学毕业证成绩单如何办理
一比一原版西悉尼大学毕业证成绩单如何办理一比一原版西悉尼大学毕业证成绩单如何办理
一比一原版西悉尼大学毕业证成绩单如何办理
 

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