DEV Community

sium_hossain
sium_hossain

Posted on • Edited on

3

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 -

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more