首页 > 编程 > Python > 正文

Django model 中设置联合约束和联合索引的方法

2019-11-25 12:05:20
字体:
来源:转载
供稿:网友

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

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

以上这篇Django model 中设置联合约束和联合索引的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表