django models索引_sql – 为什么Django显式地在唯一字段上创建索引

更新:进一步简化实验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约束创建隐式索引.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值