带有多对多字段和中间表的模型的Django查询集中的不必要联接

时间:2019-01-23 14:26:57

标签: python django orm django-orm django-2.1

当我尝试获取模型FabricCategory的所有对象时,它将返回一些重复项。我在SQL查询中发现不必要的LEFT OUTER JOIN:

python manage.py shell_plus --print-sql

>>> FabricCategory.objects.all()
SELECT `product_fabriccategory`.`id`,
       `product_fabriccategory`.`price_impact`,
       `product_fabriccategory`.`code`,
       `product_fabriccategory`.`active`
  FROM `product_fabriccategory`
  LEFT OUTER JOIN `product_fabriccategoryfabric`
    ON (`product_fabriccategory`.`id` = `product_fabriccategoryfabric`.`fabriccategory_id`)
 ORDER BY `product_fabriccategoryfabric`.`position` ASC,
          `product_fabriccategoryfabric`.`fabriccategory_id` ASC
 LIMIT 21

这是我的设置:

class FabricCategoryFabric(models.Model):
    fabriccategory = models.ForeignKey(
        'FabricCategory', related_name='fabriccategory_fabrics', on_delete=models.DO_NOTHING, null=True)
    fabric = models.ForeignKey(
        'Fabric', related_name='fabriccategory_fabrics', on_delete=models.DO_NOTHING, null=True, blank=True)
    position = models.IntegerField(default=0)

    class Meta:
        ordering = ['position', 'fabriccategory_id']


class FabricCategory(models.Model):
    price_impact = models.FloatField(default=1)
    code = models.CharField(unique=True, max_length=50, null=True)
    active = models.BooleanField(default=True)
    fabrics = models.ManyToManyField(
        'Fabric', related_name='fabric_fabriccategory',
        through='FabricCategoryFabric',
        through_fields=('fabriccategory', 'fabric'))

    class Meta:
        verbose_name_plural = "fabric categories"
        ordering = ['fabriccategory_fabrics']

    def __str__(self):
        return str(self.price_impact)


class Fabric(models.Model):
    fabric_category = models.ForeignKey(
        FabricCategory, null=True, on_delete=models.DO_NOTHING)
    reference = models.CharField(unique=True, max_length=50)
    content = models.TextField(blank=True)
    thumbnail = models.CharField(max_length=50, blank=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.reference

    class Meta:
        ordering = ['fabric_fabriccategory']

有人遇到并解决了这个问题吗? 我在用着: Django 2.1.1 mysqlclient 1.3.13 数据库引擎django.db.backends.mysql

1 个答案:

答案 0 :(得分:0)

由于您指定了ordering = ['fabric_fabriccategory'],因此默认情况下,所有查询都将联接到FabricCategoryFabric的表中。