from django.contrib.postgres.operations import TrigramExtension from django.db import migrations def create_trgm_indexes(apps, schema_editor): if schema_editor.connection.vendor != "postgresql": return quote = schema_editor.quote_name address = quote(apps.get_model("address", "AddressObject")._meta.db_table) house = quote(apps.get_model("address", "House")._meta.db_table) schema_editor.execute( f"CREATE INDEX IF NOT EXISTS addr_name_trgm ON {address} " f"USING gin (replace(lower(name), 'ё', 'е') gin_trgm_ops)" ) schema_editor.execute( f"CREATE INDEX IF NOT EXISTS house_number_trgm ON {house} " f"USING gin (house_number gin_trgm_ops)" ) schema_editor.execute( f"CREATE INDEX IF NOT EXISTS house_add1_trgm ON {house} " f"USING gin (additional_number_1 gin_trgm_ops)" ) schema_editor.execute( f"CREATE INDEX IF NOT EXISTS house_add2_trgm ON {house} " f"USING gin (additional_number_2 gin_trgm_ops)" ) def drop_trgm_indexes(apps, schema_editor): if schema_editor.connection.vendor != "postgresql": return for name in ("addr_name_trgm", "house_number_trgm", "house_add1_trgm", "house_add2_trgm"): schema_editor.execute(f"DROP INDEX IF EXISTS {schema_editor.quote_name(name)}") class Migration(migrations.Migration): dependencies = [ ("address", "0001_initial"), ] operations = [ TrigramExtension(), migrations.RunPython(create_trgm_indexes, drop_trgm_indexes), ]