SlideShare a Scribd company logo
Chapter 10
Advanced Model
Anne Lai
Django Girls meetup
2015/10/8
Django
Book
• Related Objects
• Making Changes to a Database Schema
• Manager
• Model Methods
• Executing Raw SQL Queries
Outline
Recall of Chapter 5
• Define models
• Use the database API to create,
retrieve, update and delete records
Related Objects
Related Objects
• ForeignKey
• ManyToManyField
Related Objects
Related Objects
✐return QuerySet values
instead of model instances
Related Objects
✐ book_set = lowercase(Book) + “_set”
QuerySet
Making Changes to a Database Schema
Making Changes to a Database Schema
• syncdb
 sync model to the database
 merely creates tables that don’t yet exist in database
 does not sync changes in models or perform deletions of models
Making Changes to a Database Schema
• Adding Fields
• Removing (normal/ Many-to-Many) Fields
• Removing Models
Adding Fields
Development Environment
1. Add the field to your model
✐a database column will contain
NULL values when first created.
Adding Fields
2. Run manage.py sqlall [app] to see the new CREATE TABLE statement for the
model
Development Environment
✐column definition for the new field
Adding Fields
3. Start database’s interactive shell
(e.g., psql or mysql, or you can use manage.py dbshell)
Execute an ALTER TABLE statement that adds your new column
Development Environment
NULL column
NOT NULL column
Adding Fields
4. Verify with Python interactive shell manage.py shell
Development Environment
✐ If a model contains a field that has not yet
been created in the database table, it will cause
an error happens at code execution time.
Adding Fields
Development Environment
1. Add the field to your model.
2. Run manage.py sqlall [app] to see the new CREATE TABLE statement for the
model. Note the column definition for the new field.
3. Start database’s interactive shell (e.g., psql or mysql, or you can use
manage.py dbshell). Execute an ALTER TABLE statement that adds your
new column.
4. Verify with Python interactive shell manage.py shell by importing the
model and selecting from the table (e.g., MyModel.objects.all()[:5]).
Adding Fields
Production Server
1. Start database’s interactive shell (e.g., psql or mysql, or you can use
manage.py dbshell)
2. Execute the ALTER TABLE statement
3. Add the field to your model. If you’re using source-code revision control
and you checked in your change in development environment step 1,
now is the time to update the code (e.g., svn update, with Subversion) on
the production server
4. Restart the Web server
Removing Fields
1. Remove the field from model and restart the Web server.
2. Remove the column from your database, using a command like this:
✐ Order sensitive
1. Remove the ManyToManyField from model and restart the Web server.
2. Remove the many-to-many table from your database,
using a command like this:
Normal Field
Many-to-Many Field
Removing Models
1. Remove the model from your models.py file and restart the Web server.
2. Remove the table from your database, using a command like this:
✐ Order sensitive
Manager
Manager
• Adding Extra Manager Methods
• Modifying Initial Manager QuerySets
• Multiple Managers
✐ Managers = database queries
Adding Extra Manager Methods
Adding Extra Manager Methods
✐ manager itself (objects)
✐ extends django.db.models.Manager
✐ replacing the “default” manager
Modifying Initial Manager QuerySets
QuerySet
Multiple Managers
✐ Django interprets the first Manager
defined in a class as the “default” Manager
Model Methods
Model Methods
http://www.python.org/download/releases/2.2/descrintro/#property
✐property(fget=None, fset=None, fdel=None, doc=None)
• Model Method:
 “row-level” functionality to objects
 Act on a particular model instance
• Managers:
 “table-wide” or “table-level”
Comparison
Executing Raw SQL Queries
Executing Raw SQL Queries
✐ current db connection
✐use placeholders rather than adding
parameters directly within the SQL
standard Python “DB-API”: https://www.python.org/dev/peps/pep-0249/
Thank you

More Related Content

PDF
Django design-patterns
PPTX
Powerful Generic Patterns With Django
PDF
Two scoopsofdjango ch16 dealing with the user model
PDF
The Django Book, Chapter 16: django.contrib
PDF
Advanced Django
PDF
Class-based views with Django
PDF
Two scoopsofdjango common patterns for forms
PDF
Django Patterns - Pycon India 2014
Django design-patterns
Powerful Generic Patterns With Django
Two scoopsofdjango ch16 dealing with the user model
The Django Book, Chapter 16: django.contrib
Advanced Django
Class-based views with Django
Two scoopsofdjango common patterns for forms
Django Patterns - Pycon India 2014

What's hot (20)

PDF
Two Scoops of Django - Common Patterns for Forms
PPTX
Sencha / ExtJS : Object Oriented JavaScript
PDF
Template rendering in rails
KEY
Django Pro ORM
KEY
Django Admin: Widgetry & Witchery
PPT
Django Forms: Best Practices, Tips, Tricks
PPTX
DJango admin interface
KEY
Advanced Django ORM techniques
PPTX
EAV Sytem- Magento EAV Model
PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
Forms, Getting Your Money's Worth
PDF
Implementation of EAV pattern for ActiveRecord models
PDF
ORM in Django
PDF
날로 먹는 Django admin 활용
PDF
Best Practices for Magento Debugging
PPTX
Introduction to Design Patterns in Javascript
KEY
What's new in Django 1.2?
PDF
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Two Scoops of Django - Common Patterns for Forms
Sencha / ExtJS : Object Oriented JavaScript
Template rendering in rails
Django Pro ORM
Django Admin: Widgetry & Witchery
Django Forms: Best Practices, Tips, Tricks
DJango admin interface
Advanced Django ORM techniques
EAV Sytem- Magento EAV Model
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Forms, Getting Your Money's Worth
Implementation of EAV pattern for ActiveRecord models
ORM in Django
날로 먹는 Django admin 활용
Best Practices for Magento Debugging
Introduction to Design Patterns in Javascript
What's new in Django 1.2?
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Ad

Viewers also liked (6)

PDF
12 tips on Django Best Practices
PDF
Ch9 .Best Practices for Class-Based Views
PDF
Django Worst Practices
PDF
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
PDF
Django in the Real World
PDF
The Best (and Worst) of Django
12 tips on Django Best Practices
Ch9 .Best Practices for Class-Based Views
Django Worst Practices
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
Django in the Real World
The Best (and Worst) of Django
Ad

Similar to Django: Advanced Models (20)

PPTX
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
PDF
Sql Server 2014 Course Content
PPTX
Django Schema Evolution for 5th sem.pptx
PPTX
Javascript Common Design Patterns
PDF
Ruby on Rails Kickstart 103 & 104
PPTX
Getting Started with MySQL II
PDF
Data Migrations in the App Engine Datastore
PDF
The Joy of Subforms with Randy Carey
PDF
Data herding
PDF
Data herding
DOC
Obiee metadata development
PDF
td_mxc_rubyrails_shin
PDF
td_mxc_rubyrails_shin
PDF
Staging Drupal 8 31 09 1 3
PPT
Synapseindia dot net development chapter 8 asp dot net
PPTX
Django model create a table in django web framework
PDF
Drupal upgrades and migrations. BAD Camp 2013 version
PDF
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
PDF
Entity Framework Core Cookbook 2nd Edition Ricardo Peres
PDF
Object Oriented Programming with Laravel - Session 6
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Sql Server 2014 Course Content
Django Schema Evolution for 5th sem.pptx
Javascript Common Design Patterns
Ruby on Rails Kickstart 103 & 104
Getting Started with MySQL II
Data Migrations in the App Engine Datastore
The Joy of Subforms with Randy Carey
Data herding
Data herding
Obiee metadata development
td_mxc_rubyrails_shin
td_mxc_rubyrails_shin
Staging Drupal 8 31 09 1 3
Synapseindia dot net development chapter 8 asp dot net
Django model create a table in django web framework
Drupal upgrades and migrations. BAD Camp 2013 version
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
Entity Framework Core Cookbook 2nd Edition Ricardo Peres
Object Oriented Programming with Laravel - Session 6

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Electronic commerce courselecture one. Pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Big Data Technologies - Introduction.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
KodekX | Application Modernization Development
PDF
Encapsulation theory and applications.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Spectroscopy.pptx food analysis technology
PDF
Network Security Unit 5.pdf for BCA BBA.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Digital-Transformation-Roadmap-for-Companies.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Electronic commerce courselecture one. Pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Big Data Technologies - Introduction.pptx
MIND Revenue Release Quarter 2 2025 Press Release
KodekX | Application Modernization Development
Encapsulation theory and applications.pdf
Encapsulation_ Review paper, used for researhc scholars
Spectroscopy.pptx food analysis technology
Network Security Unit 5.pdf for BCA BBA.

Django: Advanced Models

  • 1. Chapter 10 Advanced Model Anne Lai Django Girls meetup 2015/10/8 Django Book
  • 2. • Related Objects • Making Changes to a Database Schema • Manager • Model Methods • Executing Raw SQL Queries Outline
  • 3. Recall of Chapter 5 • Define models • Use the database API to create, retrieve, update and delete records
  • 7. Related Objects ✐return QuerySet values instead of model instances
  • 8. Related Objects ✐ book_set = lowercase(Book) + “_set” QuerySet
  • 9. Making Changes to a Database Schema
  • 10. Making Changes to a Database Schema • syncdb  sync model to the database  merely creates tables that don’t yet exist in database  does not sync changes in models or perform deletions of models
  • 11. Making Changes to a Database Schema • Adding Fields • Removing (normal/ Many-to-Many) Fields • Removing Models
  • 12. Adding Fields Development Environment 1. Add the field to your model ✐a database column will contain NULL values when first created.
  • 13. Adding Fields 2. Run manage.py sqlall [app] to see the new CREATE TABLE statement for the model Development Environment ✐column definition for the new field
  • 14. Adding Fields 3. Start database’s interactive shell (e.g., psql or mysql, or you can use manage.py dbshell) Execute an ALTER TABLE statement that adds your new column Development Environment NULL column NOT NULL column
  • 15. Adding Fields 4. Verify with Python interactive shell manage.py shell Development Environment ✐ If a model contains a field that has not yet been created in the database table, it will cause an error happens at code execution time.
  • 16. Adding Fields Development Environment 1. Add the field to your model. 2. Run manage.py sqlall [app] to see the new CREATE TABLE statement for the model. Note the column definition for the new field. 3. Start database’s interactive shell (e.g., psql or mysql, or you can use manage.py dbshell). Execute an ALTER TABLE statement that adds your new column. 4. Verify with Python interactive shell manage.py shell by importing the model and selecting from the table (e.g., MyModel.objects.all()[:5]).
  • 17. Adding Fields Production Server 1. Start database’s interactive shell (e.g., psql or mysql, or you can use manage.py dbshell) 2. Execute the ALTER TABLE statement 3. Add the field to your model. If you’re using source-code revision control and you checked in your change in development environment step 1, now is the time to update the code (e.g., svn update, with Subversion) on the production server 4. Restart the Web server
  • 18. Removing Fields 1. Remove the field from model and restart the Web server. 2. Remove the column from your database, using a command like this: ✐ Order sensitive 1. Remove the ManyToManyField from model and restart the Web server. 2. Remove the many-to-many table from your database, using a command like this: Normal Field Many-to-Many Field
  • 19. Removing Models 1. Remove the model from your models.py file and restart the Web server. 2. Remove the table from your database, using a command like this: ✐ Order sensitive
  • 21. Manager • Adding Extra Manager Methods • Modifying Initial Manager QuerySets • Multiple Managers ✐ Managers = database queries
  • 23. Adding Extra Manager Methods ✐ manager itself (objects) ✐ extends django.db.models.Manager ✐ replacing the “default” manager
  • 24. Modifying Initial Manager QuerySets QuerySet
  • 25. Multiple Managers ✐ Django interprets the first Manager defined in a class as the “default” Manager
  • 28. • Model Method:  “row-level” functionality to objects  Act on a particular model instance • Managers:  “table-wide” or “table-level” Comparison
  • 29. Executing Raw SQL Queries
  • 30. Executing Raw SQL Queries ✐ current db connection ✐use placeholders rather than adding parameters directly within the SQL standard Python “DB-API”: https://www.python.org/dev/peps/pep-0249/