Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django: how to select the index type?

Tags:

python

django

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 hash vs btree indexes?


2 Answers

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',)),)

like image 119
Babar Avatar answered Sep 17 '25 23:09

Babar


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

like image 39
iklinac Avatar answered Sep 17 '25 22:09

iklinac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!