[Fixed]-Using materialized views or alternatives in django


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

    class Meta:
    managed = False

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



You can use the PostgreSQL materialized view in Django to speed up complex SELECT queries with many JOIN operations. It helps a lot if you often have to perform in Django heavy select_related and prefetch_related operations.

At the same time, if you use PostgreSQL materialized view, queries that insert, update, or delete data will take longer and consume more computing resources. It makes sense to apply this technique if complex SELECT requests occur more often than data modifications.

The underlying data will change eventually. After that, you have to update the PostgreSQL materialized view somehow. It is essential to prevent users from getting stale cached data. To update the view, you can use the save method overriding in Django models, post_save and m2m_changed signals, or PostgreSQL database triggers.

Please see the detailed example of the Django PostgreSQL materialized view in this repository. It contains the code that works, as well as explanations.

  1. PostgreSQL materialized view in Django.
  2. EagerLoadingMixin in Django REST framework serializer classes to
    solve the N+1 queries problem.
  3. Usage of the most generic viewsets.ModelViewSet to build views in
    Django REST framework fast and easy.
  4. Advanced PostgreSQL SQL Query with several Common Table Expressions
    and JSON functions.
  5. Django post_save and m2m_changed signals.
  6. Populating the Django database with fake generated data for testing.

Leave a comment