SlideShare a Scribd company logo
1 of 65
Download to read offline
SOLVING PERF ISSUES IN . ORMDJANGO
SIAN LERK LAU
linkedin.com/in/sianlerk
@kiawin
A little bit about Jewel…
We’re a Singapore-based company with offices in KL and HK too.
We’re hiring!
We’re always looking for talented developers, data scientists, data engineers, devops engineers and more!
Check out our Careers page at
https://www.jewelpaymentech.com/careers.html
Image
Jewel Paymentech
© Copyright 2018 Jewel Paymentech Pte .Ltd. – Reproduction and distribution of this presentation without written permission is
prohibited.
VISION
JOIN THE TEAM
Python Developers
React Developers
Data Scientists
Data Engineers
and many more…
Scan the QR code to
visit our Careers page:
(UN)ORTHODOX
THE JOURNEY OF AN OPTIMIZATION
Jafnee Jasmee Willy CahyadiSwee Meng
BACKGROUND
(OUR STORY)
M V P
M V P
TOOLS
(TO GET US STARTED)
browser inspection tool
code inspection tool
code profiling tool
jazzband/django-silk
ORM
(THE DJANGO WAY)
just works
just works
django documentation
D.10K
(THE CASE STUDY)
#the10kreality
REALITY
HURTS
(if not your eyes)
setting baseline
#the10kdream
process of elimination
lazy load
1
# 10k Records found
Form.objects.count()
# How many queries made?
for form in Form.objects.all():
print(form.author.name)
# 10k Records found
Form.objects.count()
# How many queries made?
for form in Form.objects.all():
print(form.author.name)
# 1+10k queries made!
Big-O Notation
# 10k Records found
Form.objects.count()
# How many queries made?
for form in Form.objects.all():
print(form.author.name)
# 1+10k queries made!
Big-O Notation
O(n+1)
one-to-one
one-to-many
many-to-many
one-to-one
one-to-many
.select_related()
# One query made
for form in Form.objects.select_related('author'):
print(form.author.name)
O(1)
many-to-many .prefetch_related()
# Two queries made, join done at python level
for form in Form.objects.prefetch_related('categories'):
for category in form.categories.all():
print(category.name)
O(2)
model object
2
#expensive
skip model object
slim data retrieval
# 10k Records found
Form.objects.count()
# List of 10k model objects
for form in Form.objects.select_related('author'):
print(book.author.name)
fat + slow
skip model object
slim data retrieval
.values()
# List of 10k dictionaries
form_qs = Form.objects.values(
'application_id',
'author__name',
'categories__name',
)
for form in form_qs:
print(
f"{form['application_id']}, "
f"{form['author__name']}, "
f"{form['categories__name']}"
)
slim + quick
skip model object
slim data retrieval
.values_list()
# List of 10k tuples
form_qs = Form.objects.values_list(
'application_id',
'author__name',
'categories__name',
)
for application_id, author, categories in form_qs:
print(f'{application_id}, {author}, {categories}')
slim + quick
skip model object
slim data retrieval
.values_list()
# List of 10k tuples
form_qs = Form.objects.values_list(
'application_id',
flat=True,
)
for application_id in form_qs:
print(f'{application_id}')
slim + quick
prove to me
from django.db import connection
# prints 0
print(len(connection.queries))
# How many queries made?
forms = list(Form.objects.values_list('id',
'categories__name'))
# prints x?
print(len(connection.queries))
print(connection.queries[-1])
# actual query performed, with time taken
{'sql': "QUERY = 'SELECT ...', 'time': '0.009'}
DRF
(serializer)
3
#slow
manual serialization
return a dict
#eww
three minutes saved
#okay...
database
agnostic
support
4
to-many relationship
string aggregation
SELECT
form.id AS form,
...
STRING_AGG(category.name, ',') AS categories,
...
GROUP BY form
...
string aggregation
SELECT
form.id AS form,
...
STRING_AGG(category.name, ',') AS categories,
...
GROUP BY form
...
string aggregation
string aggregation
#...
setdefault
get
form_qs = Form.objects.values('id', 'categories__name')
serialized_forms = {}
for id, category in form_qs:
serialized_form = serialized_forms.setdefault(
id,
{},
)
categories = serialized_form.get('categories', [])
categories.append(category)
setdefault x get
#jobdone
disclaimer
THANK YOU
linkedin.com/in/sianlerk
@kiawin

More Related Content

Similar to Solving performance issues in Django ORM

moma-django overview --> Django + MongoDB: building a custom ORM layer
moma-django overview --> Django + MongoDB: building a custom ORM layermoma-django overview --> Django + MongoDB: building a custom ORM layer
moma-django overview --> Django + MongoDB: building a custom ORM layerGadi Oren
 
From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...
From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...
From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...Connected Data World
 
How to Build a Semantic Search System
How to Build a Semantic Search SystemHow to Build a Semantic Search System
How to Build a Semantic Search SystemTrey Grainger
 
Clojure: Simple By Design
Clojure: Simple By DesignClojure: Simple By Design
Clojure: Simple By DesignAll Things Open
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
RESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicRESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicNicola Iarocci
 
Intro to PySpark: Python Data Analysis at scale in the Cloud
Intro to PySpark: Python Data Analysis at scale in the CloudIntro to PySpark: Python Data Analysis at scale in the Cloud
Intro to PySpark: Python Data Analysis at scale in the CloudDaniel Zivkovic
 
Agile Database Development with JSON
Agile Database Development with JSONAgile Database Development with JSON
Agile Database Development with JSONChris Saxon
 
Scaling business app development with Play and Scala
Scaling business app development with Play and ScalaScaling business app development with Play and Scala
Scaling business app development with Play and ScalaPeter Hilton
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesTikal Knowledge
 
Re Descubriendo A Linq
Re Descubriendo A LinqRe Descubriendo A Linq
Re Descubriendo A LinqJose Bonnin
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Deliver Business Value Faster with AWS Step Functions
Deliver Business Value Faster with AWS Step FunctionsDeliver Business Value Faster with AWS Step Functions
Deliver Business Value Faster with AWS Step FunctionsDaniel Zivkovic
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
 
Information Extraction from the Web - Algorithms and Tools
Information Extraction from the Web - Algorithms and ToolsInformation Extraction from the Web - Algorithms and Tools
Information Extraction from the Web - Algorithms and ToolsBenjamin Habegger
 
Types Working for You, Not Against You
Types Working for You, Not Against YouTypes Working for You, Not Against You
Types Working for You, Not Against YouC4Media
 

Similar to Solving performance issues in Django ORM (20)

moma-django overview --> Django + MongoDB: building a custom ORM layer
moma-django overview --> Django + MongoDB: building a custom ORM layermoma-django overview --> Django + MongoDB: building a custom ORM layer
moma-django overview --> Django + MongoDB: building a custom ORM layer
 
From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...
From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...
From Knowledge Graphs to AI-powered SEO: Using taxonomies, schemas and knowle...
 
How to Build a Semantic Search System
How to Build a Semantic Search SystemHow to Build a Semantic Search System
How to Build a Semantic Search System
 
Clojure: Simple By Design
Clojure: Simple By DesignClojure: Simple By Design
Clojure: Simple By Design
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
RESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicRESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nic
 
Intro to PySpark: Python Data Analysis at scale in the Cloud
Intro to PySpark: Python Data Analysis at scale in the CloudIntro to PySpark: Python Data Analysis at scale in the Cloud
Intro to PySpark: Python Data Analysis at scale in the Cloud
 
Agile Database Development with JSON
Agile Database Development with JSONAgile Database Development with JSON
Agile Database Development with JSON
 
Scaling business app development with Play and Scala
Scaling business app development with Play and ScalaScaling business app development with Play and Scala
Scaling business app development with Play and Scala
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 
Re Descubriendo A Linq
Re Descubriendo A LinqRe Descubriendo A Linq
Re Descubriendo A Linq
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Deliver Business Value Faster with AWS Step Functions
Deliver Business Value Faster with AWS Step FunctionsDeliver Business Value Faster with AWS Step Functions
Deliver Business Value Faster with AWS Step Functions
 
Mashing Up The Guardian
Mashing Up The GuardianMashing Up The Guardian
Mashing Up The Guardian
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Mashing Up The Guardian
Mashing Up The GuardianMashing Up The Guardian
Mashing Up The Guardian
 
Information Extraction from the Web - Algorithms and Tools
Information Extraction from the Web - Algorithms and ToolsInformation Extraction from the Web - Algorithms and Tools
Information Extraction from the Web - Algorithms and Tools
 
Types Working for You, Not Against You
Types Working for You, Not Against YouTypes Working for You, Not Against You
Types Working for You, Not Against You
 

More from Sian Lerk Lau

The journey of an (un)orthodox optimization
The journey of an (un)orthodox optimizationThe journey of an (un)orthodox optimization
The journey of an (un)orthodox optimizationSian Lerk Lau
 
Velocity. Agility. Python. (Pycon APAC 2017)
Velocity. Agility. Python. (Pycon APAC 2017)Velocity. Agility. Python. (Pycon APAC 2017)
Velocity. Agility. Python. (Pycon APAC 2017)Sian Lerk Lau
 
DevOps - Myth or Real
DevOps - Myth or RealDevOps - Myth or Real
DevOps - Myth or RealSian Lerk Lau
 
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)Sian Lerk Lau
 
Quality of life through Unit Testing
Quality of life through Unit TestingQuality of life through Unit Testing
Quality of life through Unit TestingSian Lerk Lau
 
Install Archlinux in 10 Steps (Sort of) :)
Install Archlinux in 10 Steps (Sort of) :)Install Archlinux in 10 Steps (Sort of) :)
Install Archlinux in 10 Steps (Sort of) :)Sian Lerk Lau
 

More from Sian Lerk Lau (7)

The journey of an (un)orthodox optimization
The journey of an (un)orthodox optimizationThe journey of an (un)orthodox optimization
The journey of an (un)orthodox optimization
 
Velocity. Agility. Python. (Pycon APAC 2017)
Velocity. Agility. Python. (Pycon APAC 2017)Velocity. Agility. Python. (Pycon APAC 2017)
Velocity. Agility. Python. (Pycon APAC 2017)
 
DevOps - Myth or Real
DevOps - Myth or RealDevOps - Myth or Real
DevOps - Myth or Real
 
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
 
Python and you
Python and youPython and you
Python and you
 
Quality of life through Unit Testing
Quality of life through Unit TestingQuality of life through Unit Testing
Quality of life through Unit Testing
 
Install Archlinux in 10 Steps (Sort of) :)
Install Archlinux in 10 Steps (Sort of) :)Install Archlinux in 10 Steps (Sort of) :)
Install Archlinux in 10 Steps (Sort of) :)
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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?
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
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
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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
 

Solving performance issues in Django ORM