Skip to content

Commit aa0e231

Browse files
committed
Describe indexes support in django-pgviews
1 parent dda8e6a commit aa0e231

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

README.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,10 +246,40 @@ def customer_saved(sender, action=None, instance=None, **kwargs):
246246
PreferredCustomer.refresh(concurrently=True)
247247
```
248248

249+
#### Indexes
250+
251+
As the materialized view isn't defined through the usual Django model fields, any indexes defined there won't be
252+
created on the materialized view. Luckily Django provides a Meta option called `indexes` which can be used to add custom
253+
indexes to models. `pg_views` supports defining indexes on materialized views using this option.
254+
255+
In the following example, one index will be created, on the `name` column. The `db_index=True` on the field definition
256+
for `post_code` will get ignored.
257+
258+
```python
259+
from django_pgviews import view as pg
260+
261+
262+
VIEW_SQL = """
263+
SELECT id, name, post_code FROM myapp_customer WHERE is_preferred = TRUE
264+
"""
265+
266+
class PreferredCustomer(pg.MaterializedView):
267+
sql = VIEW_SQL
268+
269+
name = models.CharField(max_length=100)
270+
post_code = models.CharField(max_length=20, db_index=True)
271+
272+
class Meta:
273+
managed = False # don't forget this, otherwise Django will think it's a regular model
274+
indexes = [
275+
models.Index(fields=["name"]),
276+
]
277+
```
278+
249279
#### WITH NO DATA
250280

251281
Materialized views can be created either with or without data. By default, they are created with data, however
252-
`pg-views` supports creating materialized views without data, by defining `with_data = False` for the
282+
`pg_views` supports creating materialized views without data, by defining `with_data = False` for the
253283
`pg.MaterializedView` class. Such views then do not support querying until the first
254284
refresh (raising `django.db.utils.OperationalError`).
255285

@@ -282,6 +312,11 @@ which enables the feature when running `migrate`. The command `sync_pgviews` use
282312
however it also has switches `--enable-materialized-views-check-sql-changed` and
283313
`--disable-materialized-views-check-sql-changed` which override this setting for that command.
284314

315+
This feature also takes into account indexes. When a view is deemed not needing recreating, the process will still
316+
check the indexes on the table and delete any extra indexes and create any missing invoices. This reconciliation
317+
is done through the index name, so if you use custom names for your indexes, it might happen that it won't get updated
318+
on change of the content but not the name.
319+
285320
### Custom Schema
286321

287322
You can define any table name you wish for your views. They can even live inside your own custom

0 commit comments

Comments
 (0)