带有多个字段和中间选项卡的模型的Django queryset中不必要的连接

2024-09-30 16:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试获取model fabriccegory的所有对象时,它会返回一些重复的对象。我在sql查询中发现了不必要的左外联接:

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.后端.mysql文件


Tags: nameselfidtruedefaultmodelsproductnull