不必要地加入具有多对多字段和中间的模型的 django 查询集 table

Unnecessary join in django queryset of model with many-to-many field and intermediate table

当我尝试获取模型 FabricCategory 的所有对象时,它 returns 有一些重复项。我在 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']

有没有人遇到并解决了这个问题? 我在用着: 姜戈 2.1.1 我的sql客户端 1.3.13 数据库引擎 django.db.backends.mysql

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