9

I know that Django automatically generates indexes for foreign keys unless we define the field with db_index=False. I have read it in django doc

But I don't know if it is possible to choose the index name, or how django chooses it.

It's always something like "tablename_xxxxxx".

"xxxxx" are like random characters?

EDITED: I've discovered that "xxxx" is some codification from the model field name, but I still don't know whether we can choose an explicit name

2
  • is the xxx part something like _ibfk_1? Commented May 6, 2016 at 15:01
  • In my real case the full index name is tablename_dbaea34e, but these characters have no sense for me Commented May 6, 2016 at 15:02

3 Answers 3

6

As far as I know, there's no way to choose the name of the index. It's actually dynamically computed and it implies the hash of the table name and the column names.

See for instance the code source here, even though it's for a particular version of Django, I'm not aware of any changes towards a user named index.

Sign up to request clarification or add additional context in comments.

1 Comment

Knowing is not easily possible I can spend my time looking for another solution. Thanks.
2

Is it possible to choose the index name? yes but there isn't any benefit in doing so.

The first step is to switch off the constraint, then you need to manually add one into the migration in the form of a migrations.RunSQL yes, it's a lot of hard work and totally not worth doing.

2 Comments

I didn't thought of this solution, but you are totally right that is too much hard work. The point is that I renamed a FK after creating it, then I added another FK which had (fortuitously) the same name that de old one, and Django was trying to create an index that was already created. Obviously is a remote case, and it has other solutions, but I was curious. +1
Unless Django has an undocumented way to cluster on an index, a manually named index (plus a RunSQL to cluster) is the only way to cluster the database for efficiency.
0

From django 2.2 and ahead (I believe) the index name can be set by using the model index in the Meta class of the Model. Here the docs

from django.db import models

class MyModel(models.Model):
    my_field = models.IntegerField()

    class Meta:
        indexes = [
            models.Index(fields=['my_field'], name='my_index_field_name')
        ]

Comments

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.