The Django Book—Models
Sharre Chen
http://django-book.readthedocs.org/en/latest/index.html
The “Dumb” Way to Do Database Queries
in Views
Django’s database API
MVC
M(Model): data access logic, is handled by
Django’s database layer
V(View): business logic, is handled by views and
templates.
C(Controller): presentation logic, is handled by the
framework itself by following your URLconf and
calling the appropriate Python function.
MTV
M(Model): data access layer.
T(Template): the presentation layer.
V(View): business logic layer.
Configuring the Database
• In settings.py:
Example for MySQL:
DATABASE_ENGINE = 'mysql'	
DATABASE_NAME = 'mydb'	
DATABASE_USER= 'user'	
DATABASE_PASSWORD = 'password'	
DATABASE_HOST = ‘/var/run/mysql'	
!
Try if setting is correct:	
$ python manage.py shell	
>>> from django.db import connection	
>>> cursor = connection.cursor()
What’s the difference between a project and
an app?
• A project is an instance of a certain set of Django
apps, plus the configuration for those apps.
• An app is a portable set of Django functionality,
usually including models and views, that lives
together in a single Python package.
★if you’re using Django’s database layer (models),
you must create a Django app.
Create an app
create a books app:
$ python manage.py startapp books	
file structure will look like:
Data access with Django
Installing the Model
Edit setting.py file again:
!
!
!
!
Check models’ syntax
checks whether your models’ syntax and logic are
correct:
$ python manage.py validate
check create table sql
If your models are valid, run the following command
for Django to generate CREATE TABLE statements
for your models in the books app (before migration):
$ python manage.py sqlall books
commit the SQL to database
$ python manage.py syncdb	
!
!
★ Note that syncdb does not sync changes
in models or deletions of models.
Basic data access
Try it out:	
$ python manage.py shell
Basic data access
If you want to create an object and save it to
the database in a single step, use the
objects.create() method.
Adding Model String Representations
it difficult to tell the Publisher objects apart:
Inserting and Updating Data
update name:

will result in:
Selecting Objects
if you type command:

This roughly translates to this SQL:	
!
✦ Zen of Python: “Explicit is better than
implicit.”
Filtering Data
filter data:

This roughly translates to this SQL:	
!
Filtering Data: LIKE
filter data:

!
here, the __contains part gets translated by
Django into a SQL LIKE statement:	
!
Retrieving Single Objects
get single data:

will result in:	
!
!
you may write:
Ordering Data
get ordered data:

SQL will be:	
!
To order by multiple fields:	
!
specify reverse ordering:
Ordering Data
Specify a default ordering in model:

Chaining Lookups
get filtered and ordered data:	
!
As SQL:

Slicing Data
get first ordered data:	
!
As SQL:

Slicing Data
but can not do:	
!
!
you can do in another way:

Updating Multiple Objects in One Statement
update a filed:	
!
!
update will return success updated object number:	


Deleting Objects
delete a data:	
!
!
delete all matched data:	


Q&A
Thank You ~ :)

More Related Content

PPTX
Tango with django
KEY
Making Django and NoSQL Play Nice
PDF
Django Overview
ODP
Introduction to Django
KEY
Geotalk presentation
PDF
Working with the django admin
PPTX
An Overview of Models in Django
PPTX
Why Django for Web Development
Tango with django
Making Django and NoSQL Play Nice
Django Overview
Introduction to Django
Geotalk presentation
Working with the django admin
An Overview of Models in Django
Why Django for Web Development

What's hot (20)

PDF
Django Mongodb Engine
PPT
Django and Mongoengine
PPTX
The Django Web Application Framework 2
PDF
Understanding backbonejs
PPTX
Javascript first-class citizenery
PPTX
PDF
Django a whirlwind tour
PDF
Create responsive websites with Django, REST and AngularJS
PDF
In-depth changes to Drupal 8 javascript
PDF
Viking academy backbone.js
PDF
Intro To Mvc Development In Php
PDF
Django Heresies
PDF
Django for mobile applications
PPTX
AngularJS Architecture
PDF
Django design-patterns
PDF
Building Pluggable Web Applications using Django
PDF
Two scoops of django 1.6 - Ch7, Ch8
PDF
Hybrid Web Applications
PDF
Kiss PageObjects [01-2017]
PDF
Improving the performance of Odoo deployments
Django Mongodb Engine
Django and Mongoengine
The Django Web Application Framework 2
Understanding backbonejs
Javascript first-class citizenery
Django a whirlwind tour
Create responsive websites with Django, REST and AngularJS
In-depth changes to Drupal 8 javascript
Viking academy backbone.js
Intro To Mvc Development In Php
Django Heresies
Django for mobile applications
AngularJS Architecture
Django design-patterns
Building Pluggable Web Applications using Django
Two scoops of django 1.6 - Ch7, Ch8
Hybrid Web Applications
Kiss PageObjects [01-2017]
Improving the performance of Odoo deployments
Ad

Viewers also liked (14)

PPTX
DOCX
Muhammad abbas ansari
DOC
sreeram cv 2016
PDF
LFZH Final Report
PDF
Plano de ensino 2016 adm da produção e operações 1
PDF
Programma sinergia
PDF
Plano de ensino 2016 adm da produção e operações 2 (salvo automaticamente)
PDF
Mat ii aula captulo 1.3 parte 1
PDF
Plano de ensino 2016 adm financeira e orçamentária II plano
PDF
Materiais ii unidade 1.3 2º parte
PDF
Administração financeira e orçamentária ii aula 03
PPTX
Ppt green revolution
PDF
Material Administração da Produção e Operações I
PDF
Logística empresarial
Muhammad abbas ansari
sreeram cv 2016
LFZH Final Report
Plano de ensino 2016 adm da produção e operações 1
Programma sinergia
Plano de ensino 2016 adm da produção e operações 2 (salvo automaticamente)
Mat ii aula captulo 1.3 parte 1
Plano de ensino 2016 adm financeira e orçamentária II plano
Materiais ii unidade 1.3 2º parte
Administração financeira e orçamentária ii aula 03
Ppt green revolution
Material Administração da Produção e Operações I
Logística empresarial
Ad

Similar to The Django Book - Chapter 5: Models (20)

PDF
A gentle intro to the Django Framework
PDF
The Django Book chapter 5 Models
PPTX
Session 2 django material for training at baabtra models
PDF
Data Migrations in the App Engine Datastore
PDF
Data access
PDF
django_introduction20141030
PPTX
SQL to NoSQL: Top 6 Questions
PPTX
4 jdbc step1
PDF
9 Python programming notes for ktu physics and computer application semester 4
PPTX
Planbox Backbone MVC
PPTX
Linq to sql
PPTX
PATTERNS07 - Data Representation in C#
PPTX
ADO.NET by ASP.NET Development Company in india
PPTX
Web development with django - Basics Presentation
PPTX
Schema webinar
PPTX
Zend Framework And Doctrine
PPTX
SharePoint Saturday Atlanta 2015
PPTX
How do i connect to that
PPT
Why is data independence (still) so important? Optiq and Apache Drill.
A gentle intro to the Django Framework
The Django Book chapter 5 Models
Session 2 django material for training at baabtra models
Data Migrations in the App Engine Datastore
Data access
django_introduction20141030
SQL to NoSQL: Top 6 Questions
4 jdbc step1
9 Python programming notes for ktu physics and computer application semester 4
Planbox Backbone MVC
Linq to sql
PATTERNS07 - Data Representation in C#
ADO.NET by ASP.NET Development Company in india
Web development with django - Basics Presentation
Schema webinar
Zend Framework And Doctrine
SharePoint Saturday Atlanta 2015
How do i connect to that
Why is data independence (still) so important? Optiq and Apache Drill.

Recently uploaded (20)

PDF
737-MAX_SRG.pdf student reference guides
PPTX
Information Storage and Retrieval Techniques Unit III
PDF
Soil Improvement Techniques Note - Rabbi
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PPTX
introduction to high performance computing
PPTX
Current and future trends in Computer Vision.pptx
PDF
Abrasive, erosive and cavitation wear.pdf
PPTX
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PPTX
"Array and Linked List in Data Structures with Types, Operations, Implementat...
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
Design Guidelines and solutions for Plastics parts
PPT
Total quality management ppt for engineering students
PPTX
Module 8- Technological and Communication Skills.pptx
PDF
Visual Aids for Exploratory Data Analysis.pdf
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
737-MAX_SRG.pdf student reference guides
Information Storage and Retrieval Techniques Unit III
Soil Improvement Techniques Note - Rabbi
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
introduction to high performance computing
Current and future trends in Computer Vision.pptx
Abrasive, erosive and cavitation wear.pdf
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Fundamentals of Mechanical Engineering.pptx
Exploratory_Data_Analysis_Fundamentals.pdf
"Array and Linked List in Data Structures with Types, Operations, Implementat...
Fundamentals of safety and accident prevention -final (1).pptx
Design Guidelines and solutions for Plastics parts
Total quality management ppt for engineering students
Module 8- Technological and Communication Skills.pptx
Visual Aids for Exploratory Data Analysis.pdf
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF

The Django Book - Chapter 5: Models