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會在一個唯一的列上創(chuàng)建索引呢?也許理由是它使用運算符類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約束創(chuàng)建隱式索引.
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的django models索引_sql – 为什么Django显式地在唯一字段上创建索引的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bat脚本中如何多次键盘输入并判断_电脑
- 下一篇: 解析mysqlbinlog日志_mysq