Skip to content

Commit

Permalink
Added a class to remove any indexes for a column
Browse files Browse the repository at this point in the history
  • Loading branch information
hirensoni913 committed Jun 5, 2024
1 parent 6512cf7 commit cba04a4
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions core/services/utils/remove_indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from django.db import connection, migrations


class RemoveIndexForField(migrations.RunPython):
def __init__(self, app_name, model_name, field_name) -> None:
self.app_name = app_name
self.model_name = model_name
self.field_name = field_name
super().__init__(self.remove_index, self.reverse_remove_index)

def remove_index(self, app, schema_editor):
model = app.get_model(self.app_name, self.model_name)
field = model._meta.get_field(self.field_name)

with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(cursor, model._meta.db_table)
for constraint_name, constraint_info in constraints.items():
if constraint_info["index"] and any(field.column.lower() == col.lower() for col in constraint_info["columns"]):
cursor.execute(f"DROP INDEX {constraint_name} ON {model._meta.db_table}")

def reverse_remove_index(self, app, schema_editor):
pass

0 comments on commit cba04a4

Please sign in to comment.