DEV Community

sium_hossain
sium_hossain

Posted on • Updated on

How to create GIN index in Django migration

In your models.py file import

from django.contrib.postgres.indexes import GinIndex
Enter fullscreen mode Exit fullscreen mode

In class Meta create your index by your model field -

    class Meta:
        indexes = [
            GinIndex(name='NewGinIndex',fields=['title','keywords','shortDescription','details'])
        ]
Enter fullscreen mode Exit fullscreen mode

Then run python manage.py makemigrations and when you run python manage.py migrate you will get an error like this -

data type character varying has no default operator class for access method "gin"
HINT: You must specify an operator class for the index or define a default operator class for the data type.
data type character varying has no default operator class for access method

Then go to your app -> migrations -> _modelName_giniIndexname.py file

Then in <number>_modelName_giniIndexname.py file import

from django.contrib.postgres.operations import BtreeGinExtension
Enter fullscreen mode Exit fullscreen mode

And also in operations list add -

BtreeGinExtension(),
Enter fullscreen mode Exit fullscreen mode

Then you can run migrate. Probably you will get another error some kind of super user issue. To resolve this issue
Login psql by current user via -

sudo -u postgres psql
Enter fullscreen mode Exit fullscreen mode

then ->

postgres-# alter role <user_name> superuser;
Enter fullscreen mode Exit fullscreen mode

this user should be in your database config user profile -
Permission denied to create extension HINT: Must be superuser to create this extension postgres"/>

then ->

postgres-# CREATE EXTENSION btree_gin;
Enter fullscreen mode Exit fullscreen mode

If you want alter super user permission by after login with current user in psql -

postgres-# alter role <user_name> nosuperuser;
Enter fullscreen mode Exit fullscreen mode

exit from database by -

\q 
Enter fullscreen mode Exit fullscreen mode

then python manage.py migrate

Thank you...

😇 Read more -

Top comments (0)