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

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

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/