SlideShare uma empresa Scribd logo
1 de 55
Baixar para ler offline
A Related Matter: 
Optimizing your webapp by using django-debug-toolbar, 
select_related(), and prefetch_related() 
Christopher Adams 
DjangoCon 2014 
https://github.com/adamsc64/a-­‐related-­‐matter
Christopher Adams 
• Software Engineer at Venmo 
• Twitter/Github: @adamsc64 
• I’m not Chris Adams (@acdha), who works at 
Library of Congress 
• Neither of us are “The Gentleman” Chris Adams 
(90’s-era Professional Wrestler)
Django is great 
But Django is really a set of tools
Tools are great 
But tools can be used in good or bad ways
The Django ORM: 
A set of tools
Manage your own 
expectations for tools 
• Many people approach a new tool with broad set 
of expectations as to what the think it will do for 
them. 
• This may have little correlation with what the 
project actually has implemented.
As amazing as it 
would be if they did…
Unicorns don’t exist
The Django ORM: 
An abstraction layer
Abstraction layers 
• Great because they take us away from the 
messy details 
• Risky because they take us away from the 
messy details
Don’t forget 
You’re far from the ground
The QuerySet API
QuerySets are Lazy
QuerySets are 
Immutable
Lazy: Does not evaluate 
until it needs to
Immutable: Never 
itself changes
Each a new QuerySet, none 
hit the database 
• queryset 
= 
Model.objects.all() 
• queryset 
= 
queryset.filter(...) 
• queryset 
= 
queryset.values(...)
Hits the database 
(QuerySet is “evaluated”): 
• queryset 
= 
list(queryset) 
• queryset 
= 
queryset[:] 
• for 
model_object 
in 
queryset: 
do_something(...)
Our app: a blog
Models 
class Blog(models.Model):! 
submitter = models.ForeignKey('auth.User')! 
! 
class Post(models.Model):! 
blog = models.ForeignKey('blog.Blog', related_name="posts")! 
likers = models.ManyToManyField('auth.User')! 
! 
class PostComment(models.Model):! 
submitter = models.ForeignKey('auth.User')! 
post = models.ForeignKey('blog.Post', related_name="comments")!
List View 
def blog_list(request):! 
blogs = Blog.objects.all()! 
return render(request, "blog/blog_list.html", {! 
"blogs": blogs,! 
})!
List Template
Detail View 
def blog_detail(request, blog_id):! 
blog = get_object_or_404(Blog, id=blog_id)! 
posts = Post.objects.filter(blog=blog)! 
return render(request, "blog/blog_detail.html", {! 
"blog": blog,! 
"posts": posts,! 
})!
Detail Template
SQL Queries?
If you can’t measure 
it…
…you’d never know if 
there are problems.
First view: 
The blog list page
select_related() 
• select_related works by creating an SQL join and 
including the fields of the related object in the 
SELECT statement. 
• For this reason, select_related gets the related 
objects in the same database query. 
• However, to avoid the much larger result set that 
would result from joining across a ‘many’ 
relationship, select_related is limited to single-valued 
relationships - foreign key and one-to-one.
List View 
def blog_list(request):! 
blogs = Blog.objects.all()! 
blogs = blogs.select_related("submitter")! 
return render(request, "blog/blog_list.html", {! 
"blogs": blogs,! 
})!
Second view: 
The blog detail page
prefetch_related() 
• prefetch_related does a separate lookup for 
each relationship, and does the ’joining’ in 
Python. 
• This allows it to prefetch many-to-many and 
many-to-one objects … in addition to the 
foreign key and one-to-one relationships. 
• It also supports prefetching of GenericRelation 
and GenericForeignKey.
Detail View 
def blog_detail(request, blog_id):! 
blog = get_object_or_404(Blog, id=blog_id)! 
posts = Post.objects.filter(blog=blog)! 
posts = posts.prefetch_related(! 
“comments__submitter", "likers",! 
)! 
return render(request, "blog/blog_detail.html", {! 
"blog": blog,! 
"posts": posts,! 
})!
Summary 
• The QuerySet API methods select_related() and 
prefetch_related() automate some best practices 
to avoid extra queries in views/templates. 
• Use select_related() for one-to-many or one-to-one 
relations. 
• Use prefetch_related() for many-to-many or 
many-to-one (e.g. reverse foreign key) relations.
Thanks! 
Christopher Adams (@adamsc64) 
https://github.com/adamsc64/a-related-matter

Mais conteúdo relacionado

Destaque

A Crush on Design Thinking
A Crush on Design ThinkingA Crush on Design Thinking
A Crush on Design ThinkingMatteo Burgassi
 
Enterprise architectsview 2015-apr
Enterprise architectsview 2015-aprEnterprise architectsview 2015-apr
Enterprise architectsview 2015-aprMongoDB
 
How to use graphs to identify credit card thieves?
How to use graphs to identify credit card thieves?How to use graphs to identify credit card thieves?
How to use graphs to identify credit card thieves?Linkurious
 
GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...
GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...
GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...Neo4j
 
Exploring the Great Olympian Graph
Exploring the Great Olympian GraphExploring the Great Olympian Graph
Exploring the Great Olympian GraphNeo4j
 
Presentation on Large Scale Data Management
Presentation on Large Scale Data ManagementPresentation on Large Scale Data Management
Presentation on Large Scale Data ManagementChris Bunch
 
Web valley talk - usability, visualization and mobile app development
Web valley talk - usability, visualization and mobile app developmentWeb valley talk - usability, visualization and mobile app development
Web valley talk - usability, visualization and mobile app developmentEamonn Maguire
 
How to establish a sustainable solution for data lineage
How to establish a sustainable solution for data lineageHow to establish a sustainable solution for data lineage
How to establish a sustainable solution for data lineageLeigh Hill
 
How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...
How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...
How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...Neo4j
 
Km4City: how to make smart and resilient your city, beginner document
Km4City: how to make smart and resilient your city, beginner documentKm4City: how to make smart and resilient your city, beginner document
Km4City: how to make smart and resilient your city, beginner documentPaolo Nesi
 
The Five Graphs of Government: How Federal Agencies can Utilize Graph Technology
The Five Graphs of Government: How Federal Agencies can Utilize Graph TechnologyThe Five Graphs of Government: How Federal Agencies can Utilize Graph Technology
The Five Graphs of Government: How Federal Agencies can Utilize Graph TechnologyGreta Workman
 
Graphically understand and interactively explore your Data Lineage
Graphically understand and interactively explore your Data LineageGraphically understand and interactively explore your Data Lineage
Graphically understand and interactively explore your Data LineageMohammad Ahmed
 
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)Chris Richardson
 
Samza at LinkedIn: Taking Stream Processing to the Next Level
Samza at LinkedIn: Taking Stream Processing to the Next LevelSamza at LinkedIn: Taking Stream Processing to the Next Level
Samza at LinkedIn: Taking Stream Processing to the Next LevelMartin Kleppmann
 
Km4city Smart City Ecosystem Urban Platform
Km4city Smart City Ecosystem Urban PlatformKm4city Smart City Ecosystem Urban Platform
Km4city Smart City Ecosystem Urban PlatformPaolo Nesi
 
Data Modeling with Neo4j
Data Modeling with Neo4jData Modeling with Neo4j
Data Modeling with Neo4jNeo4j
 
Visualization of Publication Impact
Visualization of Publication ImpactVisualization of Publication Impact
Visualization of Publication ImpactEamonn Maguire
 

Destaque (20)

Don't do this
Don't do thisDon't do this
Don't do this
 
A Crush on Design Thinking
A Crush on Design ThinkingA Crush on Design Thinking
A Crush on Design Thinking
 
Enterprise architectsview 2015-apr
Enterprise architectsview 2015-aprEnterprise architectsview 2015-apr
Enterprise architectsview 2015-apr
 
How to use graphs to identify credit card thieves?
How to use graphs to identify credit card thieves?How to use graphs to identify credit card thieves?
How to use graphs to identify credit card thieves?
 
GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...
GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...
GraphConnect Europe 2016 - Creating an Innovative Task Management Engine - Mi...
 
Exploring the Great Olympian Graph
Exploring the Great Olympian GraphExploring the Great Olympian Graph
Exploring the Great Olympian Graph
 
Presentation on Large Scale Data Management
Presentation on Large Scale Data ManagementPresentation on Large Scale Data Management
Presentation on Large Scale Data Management
 
Web valley talk - usability, visualization and mobile app development
Web valley talk - usability, visualization and mobile app developmentWeb valley talk - usability, visualization and mobile app development
Web valley talk - usability, visualization and mobile app development
 
CQRS & EVS with MongoDb
CQRS & EVS with MongoDbCQRS & EVS with MongoDb
CQRS & EVS with MongoDb
 
How to establish a sustainable solution for data lineage
How to establish a sustainable solution for data lineageHow to establish a sustainable solution for data lineage
How to establish a sustainable solution for data lineage
 
How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...
How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...
How to Search, Explore and Visualize Neo4j with Linkurious - Jean Villedieu @...
 
Km4City: how to make smart and resilient your city, beginner document
Km4City: how to make smart and resilient your city, beginner documentKm4City: how to make smart and resilient your city, beginner document
Km4City: how to make smart and resilient your city, beginner document
 
The Five Graphs of Government: How Federal Agencies can Utilize Graph Technology
The Five Graphs of Government: How Federal Agencies can Utilize Graph TechnologyThe Five Graphs of Government: How Federal Agencies can Utilize Graph Technology
The Five Graphs of Government: How Federal Agencies can Utilize Graph Technology
 
Graphically understand and interactively explore your Data Lineage
Graphically understand and interactively explore your Data LineageGraphically understand and interactively explore your Data Lineage
Graphically understand and interactively explore your Data Lineage
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
 
Samza at LinkedIn: Taking Stream Processing to the Next Level
Samza at LinkedIn: Taking Stream Processing to the Next LevelSamza at LinkedIn: Taking Stream Processing to the Next Level
Samza at LinkedIn: Taking Stream Processing to the Next Level
 
Km4city Smart City Ecosystem Urban Platform
Km4city Smart City Ecosystem Urban PlatformKm4city Smart City Ecosystem Urban Platform
Km4city Smart City Ecosystem Urban Platform
 
Data Modeling with Neo4j
Data Modeling with Neo4jData Modeling with Neo4j
Data Modeling with Neo4j
 
Visualization of Publication Impact
Visualization of Publication ImpactVisualization of Publication Impact
Visualization of Publication Impact
 

Semelhante a A Related Matter: Optimizing your webapp by using django-debug-toolbar, select_related() and prefetch_related()

Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Enginethomas alisi
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developerSalvatore Fazio
 
Django Overview
Django OverviewDjango Overview
Django OverviewBrian Tol
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScriptJoost Elfering
 
Riding the Edge with Ember.js
Riding the Edge with Ember.jsRiding the Edge with Ember.js
Riding the Edge with Ember.jsaortbals
 
Build a game with javascript (april 2017)
Build a game with javascript (april 2017)Build a game with javascript (april 2017)
Build a game with javascript (april 2017)Thinkful
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14lrdesign
 
Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Salesforce Developers
 
SPSDenver - SharePoint & jQuery - What I wish I would have known
SPSDenver - SharePoint & jQuery - What I wish I would have knownSPSDenver - SharePoint & jQuery - What I wish I would have known
SPSDenver - SharePoint & jQuery - What I wish I would have knownMark Rackley
 
Google App Engine - exploiting limitations
Google App Engine - exploiting limitationsGoogle App Engine - exploiting limitations
Google App Engine - exploiting limitationsTomáš Holas
 
Hibernate Tutorial for beginners
Hibernate Tutorial for beginnersHibernate Tutorial for beginners
Hibernate Tutorial for beginnersrajkamal560066
 
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
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)Doris Chen
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 
JavaScript!
JavaScript!JavaScript!
JavaScript!RTigger
 

Semelhante a A Related Matter: Optimizing your webapp by using django-debug-toolbar, select_related() and prefetch_related() (20)

Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
Django Overview
Django OverviewDjango Overview
Django Overview
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScript
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Riding the Edge with Ember.js
Riding the Edge with Ember.jsRiding the Edge with Ember.js
Riding the Edge with Ember.js
 
Build a game with javascript (april 2017)
Build a game with javascript (april 2017)Build a game with javascript (april 2017)
Build a game with javascript (april 2017)
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14
 
Django at Scale
Django at ScaleDjango at Scale
Django at Scale
 
Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1
 
TDD with phpspec2
TDD with phpspec2TDD with phpspec2
TDD with phpspec2
 
SPSDenver - SharePoint & jQuery - What I wish I would have known
SPSDenver - SharePoint & jQuery - What I wish I would have knownSPSDenver - SharePoint & jQuery - What I wish I would have known
SPSDenver - SharePoint & jQuery - What I wish I would have known
 
Google App Engine - exploiting limitations
Google App Engine - exploiting limitationsGoogle App Engine - exploiting limitations
Google App Engine - exploiting limitations
 
Hibernate Tutorial for beginners
Hibernate Tutorial for beginnersHibernate Tutorial for beginners
Hibernate Tutorial for beginners
 
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
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 

Último

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
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
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
+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...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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...
 

A Related Matter: Optimizing your webapp by using django-debug-toolbar, select_related() and prefetch_related()

  • 1. A Related Matter: Optimizing your webapp by using django-debug-toolbar, select_related(), and prefetch_related() Christopher Adams DjangoCon 2014 https://github.com/adamsc64/a-­‐related-­‐matter
  • 2. Christopher Adams • Software Engineer at Venmo • Twitter/Github: @adamsc64 • I’m not Chris Adams (@acdha), who works at Library of Congress • Neither of us are “The Gentleman” Chris Adams (90’s-era Professional Wrestler)
  • 3.
  • 4. Django is great But Django is really a set of tools
  • 5. Tools are great But tools can be used in good or bad ways
  • 6. The Django ORM: A set of tools
  • 7. Manage your own expectations for tools • Many people approach a new tool with broad set of expectations as to what the think it will do for them. • This may have little correlation with what the project actually has implemented.
  • 8. As amazing as it would be if they did…
  • 10. The Django ORM: An abstraction layer
  • 11. Abstraction layers • Great because they take us away from the messy details • Risky because they take us away from the messy details
  • 12. Don’t forget You’re far from the ground
  • 16. Lazy: Does not evaluate until it needs to
  • 18. Each a new QuerySet, none hit the database • queryset = Model.objects.all() • queryset = queryset.filter(...) • queryset = queryset.values(...)
  • 19. Hits the database (QuerySet is “evaluated”): • queryset = list(queryset) • queryset = queryset[:] • for model_object in queryset: do_something(...)
  • 20. Our app: a blog
  • 21. Models class Blog(models.Model):! submitter = models.ForeignKey('auth.User')! ! class Post(models.Model):! blog = models.ForeignKey('blog.Blog', related_name="posts")! likers = models.ManyToManyField('auth.User')! ! class PostComment(models.Model):! submitter = models.ForeignKey('auth.User')! post = models.ForeignKey('blog.Post', related_name="comments")!
  • 22. List View def blog_list(request):! blogs = Blog.objects.all()! return render(request, "blog/blog_list.html", {! "blogs": blogs,! })!
  • 24.
  • 25. Detail View def blog_detail(request, blog_id):! blog = get_object_or_404(Blog, id=blog_id)! posts = Post.objects.filter(blog=blog)! return render(request, "blog/blog_detail.html", {! "blog": blog,! "posts": posts,! })!
  • 27.
  • 29. If you can’t measure it…
  • 30. …you’d never know if there are problems.
  • 31.
  • 32. First view: The blog list page
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38. select_related() • select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. • For this reason, select_related gets the related objects in the same database query. • However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.
  • 39. List View def blog_list(request):! blogs = Blog.objects.all()! blogs = blogs.select_related("submitter")! return render(request, "blog/blog_list.html", {! "blogs": blogs,! })!
  • 40.
  • 41.
  • 42.
  • 43. Second view: The blog detail page
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51. prefetch_related() • prefetch_related does a separate lookup for each relationship, and does the ’joining’ in Python. • This allows it to prefetch many-to-many and many-to-one objects … in addition to the foreign key and one-to-one relationships. • It also supports prefetching of GenericRelation and GenericForeignKey.
  • 52. Detail View def blog_detail(request, blog_id):! blog = get_object_or_404(Blog, id=blog_id)! posts = Post.objects.filter(blog=blog)! posts = posts.prefetch_related(! “comments__submitter", "likers",! )! return render(request, "blog/blog_detail.html", {! "blog": blog,! "posts": posts,! })!
  • 53.
  • 54. Summary • The QuerySet API methods select_related() and prefetch_related() automate some best practices to avoid extra queries in views/templates. • Use select_related() for one-to-many or one-to-one relations. • Use prefetch_related() for many-to-many or many-to-one (e.g. reverse foreign key) relations.
  • 55. Thanks! Christopher Adams (@adamsc64) https://github.com/adamsc64/a-related-matter