Django is one of the most popular Python Web framework. It is designed based on the “model-template-view” pattern. In Django, the Model is acting as the interface to the data (Database). As each model is associated with each physical table in database, I start wondering if it’s possible to make ORM deal with more advanced database feature, that is view and materialized view. The result turns out to be more than great!

View and materialized view are results of lookup SQL query. The main difference between them is that materialized view stores result as an actual table while view does not. From technical perspective, view and materialized view are good for repetitive query. They enhance query speed. From business perspective, they can be used to declare data scope for the usages of different teams/departments. The question is how we leverage this feature in Django?

Here are conclusions of my research — ORM works well with materialized view but view. It makes sense, does it? Because materialized view is a physical table. ORM should be able to associate it. Regarding view, ORM has a similar mechanism called “manager” on which I will write another article to walk you through in the future. Let’s continue our tutorial on materialized view.

Dependencies

  1. Python 3.7
  2. Django 2.2.x
  3. Psycopg2-binary 2.8.6

In this tutorial, I am going to use PostgreSQL database. Definitely choose whatever relational database you would like to use. In order to let Python “talk” to PostgreSQL database, we need to pip install psycopg2-binary. In addition, you may need to set up a local PostgreSQL database on your own machine so that models in your Django project can connect.

#django #sql #web-development #materializedviews #python3 #how to use materialized view in django

How to Use Materialized View in Django
1.95 GEEK