python - Django ManyToManyField 是否创建具有冗余索引的表?

标签 python mysql django

如果我有一个模型 Foo,它有一个简单的 M2M 字段来建模 Bar:

class Foo(Model):
    bar = ManyToManyField(Bar)

Django 似乎创建了一个表 foo_bar ,它具有以下索引:

index 1: primary, unique (id)
index 2: unique (foo_id, bar_id)
index 3: non_unique (foo_id)
index 4: non_unique (bar_id)

根据我的 SQL 基础知识,如果查询需要查找 foo_id 上的条件,索引 2 就足够了(因为最左边的列可用于查找)。索引 3 似乎是多余的。

我的假设是否正确,索引 3 确实占用了索引空间,但没有提供任何好处?我最好使用直通表并在 (foo_id, bar_id) 上手动创建唯一索引,并且可以选择在 (bar_id) 上创建另一个索引(如果需要)?

最佳答案

理解多对多关联在数据库中如何表示的关键是要认识到联结表(在本例中为 foo_bar)的每一行将左表 (foo) 中的一行与一行连接起来从右表(栏)。 “foo”的每个pk可以多次复制到“foo_bar”; “bar”的每个 pk 也可以多次复制到“foo_bar”。但“foo_bar”中的同一对 fk 只能出现一次。

因此,如果“foo_bar”中只有一个索引(“foo”或“bar”的 pk),则它只能出现一次......并且它不是多对多关系。

例如,我们有两个模型(电子商务):产品、订单。

每种产品可以有多个订单,一个订单可以包含多个产品。

class Product(models.Model):
    ...

class Order(models.Model):
    products = ManyToManyField(Product, through='OrderedProduct')


class OrderedProduct(models.Model):
    # each pair can be only one time, so in one order you can calculate price for each product (considering ordered amount of it).
    # and at the same time you can get somewhere in your template|view all orders which contain same product 

    order = models.ForeignKey(Order)
    product = models.ForeignKey(Product)

    amount = models.PositiveSmallIntegerField()  # amount of ordered products
    price = models.IntegerField()  # just int in this simple example

    def save(self, *args, **kwargs):
        self.price = self.product__price * self.amount

        super(OrderedProduct, self).save(*args, **kwargs)

关于python - Django ManyToManyField 是否创建具有冗余索引的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31095950/

相关文章:

python - python中多种方法的闭包

python - 使用一些重复元素从 CSV 文件中构建和提取多维 Python 字典中的值

java - 无法创建池 Async Jersey+Spring+Tomcat 的初始连接

Mysql确定包含标题的列的最大char_length

python - nginx+uwsgi+django,uwsgi中好像有什么奇怪的缓存,帮帮我

python - objects.get(id) 中的 Django 错误 'too many values to unpack'

python - Pandas 计算自值>当前单元格以来的行数

python - 如何在两个时间序列之间执行互相关以及我应该在 python 中执行哪些转换?

mysql - 如何存储.txt文件MySQL数据库?

django - 我可以将经理添加到多对多关系中吗?