Django 索引与联合索引

索引

索引可以极大的提高数据的查询速度,但是会降低插入、删除、更新表的速度,因为在执行这些写操作时,还要操作索引文件

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% 直接得到一万条数据

​ 建立联合索引的同时 还会给他们之间的组合建立索引
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章