更新:进一步简化实验psql的Q:
对于以下Django模型:
class Book(models.Model):
name = models.TextField(unique=True)
pg_dump(PostgreSQL 9.3)显示下表&限制:
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);
但是PostgreSQL documentation说:
PostgreSQL automatically creates a unique index when a unique
constraint […] is defined for a table.
[…] there’s
no need to manually create indexes on unique columns; doing so would
just duplicate the automatically-created index.
问题:为什么Django会在一个唯一的列上创建索引呢?也许理由是它使用运算符类text_pattern_ops,因此Django需要添加另一个索引.如果是这种情况,更好的方法是将Django解释为unique = True约束,如下所示:
CREATE UNIQUE INDEX book_name_like ON book USING btree (name text_pattern_ops);
根本没有列中的UNIQUE约束.因此,带有text_pattern_ops的单个UNIQUE INDEX将导致DB不为UNIQUE约束创建隐式索引.