There is a bit more universal and Django native way. You can use following custom Migration Operation:
class CreateJsonbObjectKeyIndex(Operation):
reversible = True
def __init__(self, model_name, field, key, index_type='btree', concurrently=False, name=None):
self.model_name = model_name
self.field = field
self.key = key
self.index_type = index_type
self.concurrently = concurrently
self.name = name
def state_forwards(self, app_label, state):
pass
def get_names(self, app_label, schema_editor, from_state, to_state):
table_name = from_state.apps.get_model(app_label, self.model_name)._meta.db_table
index_name = schema_editor.quote_name(
self.name or schema_editor._create_index_name(table_name, [f'{self.field}__{self.key}'])
)
return table_name, index_name
def database_forwards(self, app_label, schema_editor, from_state, to_state):
table_name, index_name = self.get_names(app_label, schema_editor, from_state, to_state)
schema_editor.execute(f"""
CREATE INDEX {'CONCURRENTLY' if self.concurrently else ''} {index_name}
ON {table_name}
USING {self.index_type}
(({self.field}->'{self.key}'));
""")
def database_backwards(self, app_label, schema_editor, from_state, to_state):
_, index_name = self.get_names(app_label, schema_editor, from_state, to_state)
schema_editor.execute(f"DROP INDEX {index_name};")
def describe(self):
return f'Creates index for JSONB object field {self.field}->{self.key} of {self.model_name} model'
@property
def migration_name_fragment(self):
return f'create_index_{self.model_name}_{self.field}_{self.key}'
Usage example:
from django.db import migrations
from util.migration import CreateJsonbObjectKeyIndex
class Migration(migrations.Migration):
atomic = False # Required if concurrently=True for 0 downtime background index creation
dependencies = [
('app_label', '00XX_prev_migration'),
]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=[
# Operation to run custom SQL command. Check the output of `sqlmigrate` to see the auto-generated SQL
CreateJsonbObjectKeyIndex(
model_name='User', field='meta', key='adid', index_type='HASH',
concurrently=True,
)
],
)
]
Tested with Django-2.2 and and AWS Postgres RDS, but should be compatible with other Django