1

I have created a model in Django.

class MyModel(models.Model):
    features = TextField(blank=True, default='')

There are several possible ways to store the data in the feature field. Some examples below.

  1. feature1;feature2
  2. feature1, feature2
  3. feature1,feature2

And so on. I need to create a GIN index for that field. I would probably do it in postgreSQL in the following way

CREATE INDEX features_search_idx ON "mymodel" USING gin (regexp_split_to_array("mymodel"."features", E'[,;\\s]+'));

Would it be possible to do the same thing by a migration?

1 Answer 1

2

Yes.

  • Create an empty migration: python manage.py makemigration yourapp --empty -n pour_gin
  • Add a migrations.RunSQL() operation in the migration file.
class Migration(migrations.Migration):

    dependencies = [
        # ...
    ]
    operations = [
        migrations.RunSQL(
            sql="""CREATE INDEX features_search_idx ON "mymodel" USING gin (regexp_split_to_array("mymodel"."features", E'[,;\\s]+'));""",
            reverse_sql=migrations.RunSQL.noop,  # TODO: replace me with DROP INDEX
        ),
    ]
Sign up to request clarification or add additional context in comments.

2 Comments

Is DROP INDEX essential?
If you want to be able to undo the migration at any point, it'd be nice to have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.