@@ -246,10 +246,40 @@ def customer_saved(sender, action=None, instance=None, **kwargs):
246
246
PreferredCustomer.refresh(concurrently = True )
247
247
```
248
248
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
+
249
279
#### WITH NO DATA
250
280
251
281
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
253
283
` pg.MaterializedView ` class. Such views then do not support querying until the first
254
284
refresh (raising ` django.db.utils.OperationalError ` ).
255
285
@@ -282,6 +312,11 @@ which enables the feature when running `migrate`. The command `sync_pgviews` use
282
312
however it also has switches ` --enable-materialized-views-check-sql-changed ` and
283
313
` --disable-materialized-views-check-sql-changed ` which override this setting for that command.
284
314
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
+
285
320
### Custom Schema
286
321
287
322
You can define any table name you wish for your views. They can even live inside your own custom
0 commit comments