Opened 10 years ago
Last modified 4 years ago
#24082 new Bug
Unique=True on TextField or CharField should not create an index — at Version 2
Description (last modified by ) ¶
I've experienced this with PostgreSQL but I suspect it could be true for other databases too.
PostgreSQL docs say:
there's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.
Further the docs say:
The index covers the columns that make up the [...] unique constraint [...] and is the mechanism that enforces the constraint.
However this model in Django with unique=True
on a TextField
creates an index on top of the unique constraint.
class Book(models.Model): name = models.TextField(unique=True)
creates following table & constraints in PostgreSQL:
CREATE TABLE book ( id integer NOT NULL, name text NOT NULL, ); ALTER TABLE ONLY book ADD CONSTRAINT book_name_key UNIQUE (name); CREATE INDEX book_name_like ON book USING btree (name text_pattern_ops);
Please correct me if I'm wrong. My conclusion is that database enforce unique constraint by way of an index. Adding another index is a waste. There's some mention of this fact in an old bug report (comment 3 & comment 6 ) but it looks like the issue got dropped.
However, if the justification to add a second index is Bug Report 12234 then it might be more efficient to interpret a unique=True
as
CREATE UNIQUE INDEX "book_name_like_idx" ON "book" ("name" text_pattern_ops);
instead of a UNIQUE
constraint, an INDEX
and an implicit index by the database.
According to the ticket's flags, the next step(s) to move this issue forward are:
- To provide a patch by sending a pull request. Claim the ticket when you start working so that someone else doesn't duplicate effort. Before sending a pull request, review your work against the patch review checklist. Check the "Has patch" flag on the ticket after sending a pull request and include a link to the pull request in the ticket comment when making that update. The usual format is:
[https://github.com/django/django/pull/#### PR]
.
Change History (2)
comment:1 by , 10 years ago
Description: | modified (diff) |
---|
comment:2 by , 10 years ago
Description: | modified (diff) |
---|