SlideShare a Scribd company logo
and
PostgreSQL
Materialized Views
by: Shay
Halsband
The Problem
 A real time query with growing data
 Doing a lot of joins including to itself
 Performance was degrading with data increase
The solution …
What are materialized views
a materialized view is a
database object that contains the
results of a query
REFRESH MATERIALIZED VIEW [ CONCURRENTLY ]
name
[ WITH [ NO ] DATA ]
Updating the view is
simple
Creating a view from django
CREATE MATERIALIZED VIEW table_name
[ (column_name [, ...] ) ]
[ WITH ( storage_parameter [= value] [, ... ] ) ]
[ TABLESPACE tablespace_name ]
AS query
[ WITH [ NO ] DATA ]
How do I get this
From this?
Car.objects.filter(
manufacturer__some_complicated_tbl__some_
crazy_value=10,
engine__valve__name=’Steam’
)
The Dirty Trick
Part 1 – Creating the view
raw_query, params = qs.query.sql_with_params()
As django rely on the driver to format the query
and parameters, we have to manually do it
ourselves
 Reformat the parameters
params = tuple([("'%s'" % unicode(p).replace('%', '%%'))
for p in params])
 Get the SQL query and parameters from query
set
 Execute the query
sql = ("DROP MATERIALIZED VIEW IF EXISTS
table_materialized;n“
"CREATE MATERIALIZED VIEW table_materialized
ASn"+
raw_query)
cursor = connection.cursor()
cursor.execute(sql)
raw_query = raw_query.replace('%s','{}')
.format(*params)
.replace('%', '%%')
 Reformat the query
The Dirty Trick
Part 2 – django model
 Base Model
Class BaseCar(Model):
class Meta:
abstract = True
total_km = models.IntegerField(default=0)
num_of_windows = models.IntegerField("Num of
Windows", default=6)
…
 Real Model
Class Car(BaseCar):
@classmethod
def create_materialized(cls):
…
@classmethod
def refresh_materialized(cls):
sql = "REFRESH MATERIALIZED VIEW
car_materialized“
cursor = connection.cursor()
cursor.execute(sql)
 Materialized Model
Class MaterializedCar(Model):
class Meta:
db_table = ‘car_materialized‘
managed = False
last_day_km = models.IntegerField(default=0)
…
South Migration
 If the base data changes we need to remember to
update the view.
./manage.py schemamigration roadtripapp 
update_materialized_car –empty
 Call create_materialized in the forward method
Thank You
XtremIO is looking for:
 Python developers for backend
 Angular developers for frontend

More Related Content

PDF
FleetDB: A Schema-Free Database in Clojure
PDF
FleetDB A Schema-Free Database in Clojure
PDF
Postgres Plus Cloud Database on OpenStack
PDF
Practical Google App Engine Applications In Py
PDF
Crafting [Better] API Clients
PPTX
SQL PASS 2017 - Building one million predictions per second using SQL Server ...
PPTX
Disconnected data
PDF
Optimization in django orm
FleetDB: A Schema-Free Database in Clojure
FleetDB A Schema-Free Database in Clojure
Postgres Plus Cloud Database on OpenStack
Practical Google App Engine Applications In Py
Crafting [Better] API Clients
SQL PASS 2017 - Building one million predictions per second using SQL Server ...
Disconnected data
Optimization in django orm

Similar to Materialized views and django (20)

PDF
How to teach an elephant to rock'n'roll
PPTX
Progressive Enhancment with Rails and React
PPT
Dev411
PPT
SharePoint Administration with PowerShell
PDF
Using Task Queues and D3.js to build an analytics product on App Engine
PDF
Angular 2 introduction
PDF
JSLab. Алексей Волков. "React на практике"
PDF
React table tutorial project setup, use table, and usefilter
PDF
Tactical data engineering
PDF
Automated Refactoring With IntelliJ IDEA
PDF
React lecture
PDF
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
PPT
Database Foundation Training
PDF
Dive into React Performance
PDF
Adapters db-104-informixstoredprocedure
DOCX
Android sql examples
PDF
Data Seeding via Parameterized API Requests
ODP
django.contrib.databrowse
PPTX
0205_HandsOn_orm_java_springboot_tp_4.pptx
PDF
Rapid Prototyping with PEAR
How to teach an elephant to rock'n'roll
Progressive Enhancment with Rails and React
Dev411
SharePoint Administration with PowerShell
Using Task Queues and D3.js to build an analytics product on App Engine
Angular 2 introduction
JSLab. Алексей Волков. "React на практике"
React table tutorial project setup, use table, and usefilter
Tactical data engineering
Automated Refactoring With IntelliJ IDEA
React lecture
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
Database Foundation Training
Dive into React Performance
Adapters db-104-informixstoredprocedure
Android sql examples
Data Seeding via Parameterized API Requests
django.contrib.databrowse
0205_HandsOn_orm_java_springboot_tp_4.pptx
Rapid Prototyping with PEAR
Ad

Recently uploaded (20)

PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
AutoCAD Professional Crack 2025 With License Key
PDF
Nekopoi APK 2025 free lastest update
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Cost to Outsource Software Development in 2025
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PDF
Complete Guide to Website Development in Malaysia for SMEs
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
assetexplorer- product-overview - presentation
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PPTX
history of c programming in notes for students .pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
AutoCAD Professional Crack 2025 With License Key
Nekopoi APK 2025 free lastest update
CHAPTER 2 - PM Management and IT Context
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
Odoo Companies in India – Driving Business Transformation.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Cost to Outsource Software Development in 2025
Wondershare Filmora 15 Crack With Activation Key [2025
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Complete Guide to Website Development in Malaysia for SMEs
How to Choose the Right IT Partner for Your Business in Malaysia
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
assetexplorer- product-overview - presentation
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
iTop VPN Free 5.6.0.5262 Crack latest version 2025
history of c programming in notes for students .pptx
Ad

Materialized views and django

  • 2. The Problem  A real time query with growing data  Doing a lot of joins including to itself  Performance was degrading with data increase The solution …
  • 3. What are materialized views a materialized view is a database object that contains the results of a query REFRESH MATERIALIZED VIEW [ CONCURRENTLY ] name [ WITH [ NO ] DATA ] Updating the view is simple
  • 4. Creating a view from django CREATE MATERIALIZED VIEW table_name [ (column_name [, ...] ) ] [ WITH ( storage_parameter [= value] [, ... ] ) ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ] How do I get this From this? Car.objects.filter( manufacturer__some_complicated_tbl__some_ crazy_value=10, engine__valve__name=’Steam’ )
  • 5. The Dirty Trick Part 1 – Creating the view raw_query, params = qs.query.sql_with_params() As django rely on the driver to format the query and parameters, we have to manually do it ourselves  Reformat the parameters params = tuple([("'%s'" % unicode(p).replace('%', '%%')) for p in params])  Get the SQL query and parameters from query set
  • 6.  Execute the query sql = ("DROP MATERIALIZED VIEW IF EXISTS table_materialized;n“ "CREATE MATERIALIZED VIEW table_materialized ASn"+ raw_query) cursor = connection.cursor() cursor.execute(sql) raw_query = raw_query.replace('%s','{}') .format(*params) .replace('%', '%%')  Reformat the query
  • 7. The Dirty Trick Part 2 – django model  Base Model Class BaseCar(Model): class Meta: abstract = True total_km = models.IntegerField(default=0) num_of_windows = models.IntegerField("Num of Windows", default=6) …
  • 8.  Real Model Class Car(BaseCar): @classmethod def create_materialized(cls): … @classmethod def refresh_materialized(cls): sql = "REFRESH MATERIALIZED VIEW car_materialized“ cursor = connection.cursor() cursor.execute(sql)
  • 9.  Materialized Model Class MaterializedCar(Model): class Meta: db_table = ‘car_materialized‘ managed = False last_day_km = models.IntegerField(default=0) …
  • 10. South Migration  If the base data changes we need to remember to update the view. ./manage.py schemamigration roadtripapp update_materialized_car –empty  Call create_materialized in the forward method
  • 11. Thank You XtremIO is looking for:  Python developers for backend  Angular developers for frontend