Opened 5 years ago

Closed 5 years ago

#14651 closed (invalid)

ignored field index creation for fields with unique=True and db_index=True

Reported by: jordi Owned by: nobody
Component: Database layer (models, ORM) Version: 1.2
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


If I have a field in my model like;
field = models.CharField(max_length=4, unique=True, db_index=True)

function sql_indexes_for_field from db/backends/ will silently ignore creation the index for that field.

I think it show be created or, at least, give a message that it will not be created and some reason.

To create an index for such a field I have to remove "unique=True", create
the index whith "python sqlindexes <app>" and after add again "unique=True", so django admin captures
non unique entries. I am using sqlite.

Change History (4)

comment:1 Changed 5 years ago by ramiro

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

Perhaps this is beacuase of this? (from

INTEGER PRIMARY KEY columns aside, both UNIQUE and PRIMARY KEY constraints are implemented by creating an index in the database (in the same way as a "CREATE UNIQUE INDEX" statement would). Such an index is used like any other index in the database to optimize queries. As a result, there often no advantage (but significant overhead) in creating an index on a set of columns that are already collectively subject to a UNIQUE or PRIMARY KEY constraint.

Closing the ticket, please reopen if I've misunderstood things.

comment:2 Changed 5 years ago by jordi

In the case
field = models.CharField?(max_length=4, unique=True, db_index=True)
I just need a quick access to this field, and it must be a unique. If the field is part of an other index I think it not the matter.

In the code, creation of indexes with (unique=True and db_index=True) are just ignored:

If there is a reason, the user should be warned and it should be stated in the documentation

That's all, thanks.

comment:3 Changed 5 years ago by jordi

  • Resolution invalid deleted
  • Status changed from closed to reopened

comment:4 Changed 5 years ago by russellm

  • Resolution set to invalid
  • Status changed from reopened to closed

I'm in agreement with Ramiro. A UNIQUE column *IS* indexed. You don't need to create an additional index. That's why it's optimized out of the table creation code.

Note: See TracTickets for help on using tickets.
Back to Top