简体   繁体   中英

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.

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. eg MyModel.objects.count()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM