SlideShare a Scribd company logo
1 of 31
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

What's hot

Two Scoops of Django - Common Patterns for Forms
Two Scoops of Django - Common Patterns for FormsTwo Scoops of Django - Common Patterns for Forms
Two Scoops of Django - Common Patterns for FormsVic Yang
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptRohan Chandane
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails Hung Wu Lo
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryPamela Fox
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interfaceMahesh Shitole
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniquesDaniel Roseman
 
EAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelEAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelKhoa Truong Dinh
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's WorthAlex Gaynor
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsKostyantyn Stepanyuk
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용KyeongMook "Kay" Cha
 
Best Practices for Magento Debugging
Best Practices for Magento Debugging Best Practices for Magento Debugging
Best Practices for Magento Debugging varien
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 

What's hot (20)

Two Scoops of Django - Common Patterns for Forms
Two Scoops of Django - Common Patterns for FormsTwo Scoops of Django - Common Patterns for Forms
Two Scoops of Django - Common Patterns for Forms
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & Witchery
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interface
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
 
Extjs
ExtjsExtjs
Extjs
 
EAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelEAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV Model
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's Worth
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord models
 
ORM in Django
ORM in DjangoORM in Django
ORM in Django
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
 
Best Practices for Magento Debugging
Best Practices for Magento Debugging Best Practices for Magento Debugging
Best Practices for Magento Debugging
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
What's new in Django 1.2?
What's new in Django 1.2?What's new in Django 1.2?
What's new in Django 1.2?
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 

Viewers also liked

12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best PracticesDavid Arcos
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based ViewsWilly Liu
 
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in DjangoDjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in DjangoCasey Kinsey
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 

Viewers also liked (6)

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

Similar to Django: Advanced Models

Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Udit Gangwani
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Heng-Yi Wu
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreRyan Morlok
 
The Joy of Subforms with Randy Carey
The Joy of Subforms with Randy CareyThe Joy of Subforms with Randy Carey
The Joy of Subforms with Randy Careyjdaychi
 
Obiee metadata development
Obiee metadata developmentObiee metadata development
Obiee metadata developmentdils4u
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Drupalcon Paris
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot netSynapseindiappsdevelopment
 
Drupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDrupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDavid Lanier
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Shahrzad Peyman
 
Backbone.js
Backbone.jsBackbone.js
Backbone.jsVO Tho
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Upgrading to MySQL 8.0 webinar slides November 27th, 2019
Upgrading to MySQL 8.0 webinar slides November 27th, 2019Upgrading to MySQL 8.0 webinar slides November 27th, 2019
Upgrading to MySQL 8.0 webinar slides November 27th, 2019Dave Stokes
 

Similar to Django: Advanced Models (20)

Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
 
Sql Server 2014 Course Content
Sql Server 2014 Course ContentSql Server 2014 Course Content
Sql Server 2014 Course Content
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
 
The Joy of Subforms with Randy Carey
The Joy of Subforms with Randy CareyThe Joy of Subforms with Randy Carey
The Joy of Subforms with Randy Carey
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
Obiee metadata development
Obiee metadata developmentObiee metadata development
Obiee metadata development
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
 
Drupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDrupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 version
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Upgrading to MySQL 8.0 webinar slides November 27th, 2019
Upgrading to MySQL 8.0 webinar slides November 27th, 2019Upgrading to MySQL 8.0 webinar slides November 27th, 2019
Upgrading to MySQL 8.0 webinar slides November 27th, 2019
 

Recently uploaded

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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/