Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using materialized views or alternatives in django

I need to use some aggregate data in my django application that changes frequently and if I do the calculations on the fly some performance issues may happen. Because of that I need to save the aggregate results in a table and, when data changes, update them. Because I use django some options may be exist and some maybe not. For example I can use django signals and a table that, when post_save signal is emitted, updates the results. Another option is materialized views in postgresql or indexed views in MSSQL Server, that I do not know how to use in django or if django supports them or not. What is the best way to do this in django for improving performance and accuracy of results.

like image 648
Bartanix Avatar asked Apr 18 '15 11:04

Bartanix


1 Answers

You can use Materialized view with postgres. It's very simple.

  1. You have to create a view with query like CREATE MATERIALIZED VIEW my_view as select * from my_table;
  2. Create a model with two option managed=false and db_name=my_view in the model Meta like this

    MyModel(models.Model): class Meta: managed = False db_table='my_view'

  3. Simply use powers of ORM and treat MyModel as a regular model. e.g. MyModel.objects.count()

like image 160
Aleem Avatar answered Sep 28 '22 21:09

Aleem