14👍
You can use Materialized view with postgres. It’s very simple.
- You have to create a view with query like
CREATE MATERIALIZED VIEW
my_view as select * from my_table; -
Create a model with two
optionmanaged=false
anddb_name=my_view
in the modelMeta
like
thisMyModel(models.Model):
class Meta:
managed = False
db_table='my_view' -
Simply use powers of ORM and treat MyModel as a regular model. e.g.
MyModel.objects.count()
0👍
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.
- PostgreSQL materialized view in Django.
EagerLoadingMixin
in Django REST framework serializer classes to
solve the N+1 queries problem.- Usage of the most generic
viewsets.ModelViewSet
to build views in
Django REST framework fast and easy. - Advanced PostgreSQL SQL Query with several Common Table Expressions
and JSON functions. - Django
post_save
andm2m_changed
signals. - Populating the Django database with fake generated data for testing.
- ImportError: No module named rest_framework_jwt.views
- Find django/contrib/admin/templates
- Django difference between clear() and delete()
- Django/jQuery Cascading Select Boxes?