Skip to content Skip to sidebar Skip to footer

Python Django: How To Select The Index Type?

As stated in https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_index, you can add indexes to your table using db_index=True. But how do you force

Solution 1:

Things have changed a lot since the question was asked. It is now possible to define an index in the model layer through the metaclass of your model (at least since django 1.11): https://docs.djangoproject.com/en/dev/ref/contrib/postgres/indexes/

For example:

from django.contrib.postgres.indexes import HashIndex
from django.db import models


class User(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        indexes = (HashIndex(fields=('name',)),)


Solution 2:

Django has no implemented particular index type selection through models.

Workaround would be to create empty migration and write SQL statement in your migration for consistency

https://docs.djangoproject.com/en/1.10/howto/writing-migrations/

manage.py makemigrations --empty app

Inside of migration in operations put following

migrations.RunSQL('Query to add index')

RunSQL docs


Post a Comment for "Python Django: How To Select The Index Type?"