在Django model中对一张表的几个字段进行联合约束和联合索引,例如在购物车表中,登陆的用户和商品两个字段在一块儿表示惟一记录。code
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"表示不能重复,不能同样。get
index_together = ["user", "goods"] 表示联合索引,其中"goods"和"user"联合同步查询,提升效率。同步
示例SQL:select * from person where a=100 and b=100 and c=1000;class
假设你的数据有一千万条 每次条件过滤 省10%的数据效率
1 若是三个单索引 先拿a的索引找 剩下100万数据 而后拿b条件找 剩十万 再c条件找 最后获得一万数据登录
2 若是是联合索引 他 一千万数据10% 10% * 10% 直接获得一万条数据select
创建联合索引的同时 还会给他们之间的组合创建索引model