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

定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一ffjhghh
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad EscortsCall girls in Ahmedabad High profile
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 

Recently uploaded (20)

定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 

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