索引:
索引可以極大的提高數據的查詢速度,但是會降低插入、刪除、更新表的速度,因爲在執行這些寫操作時,還要操作索引文件
Django中建立索引
class PressureSensor(models.Model):
store = models.ForeignKey(Store, verbose_name='門店ID', on_delete=models.CASCADE)
barcode = models.CharField(verbose_name='貨架碼', max_length=12, db_index=True)
當然,除了這一種方式外,還有以下兩種,分別是:
unique_together
聯合主鍵,包含index_together
index_together
組合索引
class Meta:
unique_together = [["store", "barcode"], ["store", "mac_addr_no"]]
class Meta:
index_together = ["store", "sensor"]
聯合索引:
Django索引原則:
- 主鍵必定是索引
- Django默認會爲每個Foreginkey創建一個索引
在Django model中對一張表的幾個字段進行聯合約束和聯合索引,例如在購物車表中,登錄的用戶和商品兩個字段在一起表示唯一記錄。
舉個栗子:
Django model中購物車表
class Cart(models.Model):
user = models.ForeignKey(
MyUser,
verbose_name="用戶"
)
goods = models.ForeignKey(
Goods,
verbose_name="商品"
)
num = models.IntegerField(
verbose_name="商品數量"
)
is_select = models.BooleanField(
default=True,
verbose_name="選中狀態"
)
class Meta:
# 聯合約束 其中goods和user不能重複
unique_together = ["goods", "user"]
# 聯合索引
index_together = ["user", "goods"]
# unique_together = ["goods", "user"] 表示聯合約束,其中"goods"和"user"表示不能重複,不能一樣。
# index_together = ["user", "goods"] 表示聯合索引,其中"goods"和"user"聯合同步查詢,提高效率。
聯合索引的優勢
示例SQL:select * from person where a=100 and b=100 and c=1000;
假設你的數據有一千萬條 每次條件過濾 省10%的數據
1 如果三個單索引 先拿a的索引找 剩下100萬數據 然後拿b條件找 剩十萬 再c條件找 最後得到一萬數據
2 如果是聯合索引 他 一千萬數據*10% * 10% * 10% 直接得到一萬條數據
建立聯合索引的同時 還會給他們之間的組合建立索引