我认为标题不是很准确,但我不知道如何更好地描述它。
我的模型如下所示:
class Articles(models.Model):
id = models.IntegerField(primary_key=True)
supplier = models.CharField(max_length=765, blank=True)
ref = models.CharField(max_length=180, blank=True)
ean = models.CharField(max_length=42, blank=True)
model = models.CharField(max_length=180, blank=True)
price = models.FloatField(null=True, blank=True)
stock = models.IntegerField(null=True, blank=True)
product_id = models.ForeignKey('Products', unique=True)
class Products(models.Model):
id = models.IntegerField(primary_key=True)
eans = models.TextField(blank=True)
model = models.CharField(max_length=180, blank=True)
description = models.CharField(max_length=9000, blank=True)
name = models.CharField(max_length=765, blank=True)
brand_id = models.ForeignKey('Brands', unique=True, db_column='brand_id')
category_id = models.ForeignKey('Categories', unique=True)
image = models.CharField(max_length=765, blank=True)
我想做的是获取该产品的最低价格和供应商的产品列表(可选择按类别、品牌、供应商、价格...过滤)。请记住,每种产品通常有不止一篇文章(每篇文章都有一个供应商,但两个供应商可以销售相同的产品)。
我想以最有效的方式获得此列表,但这样做需要很长时间:
Products.objects.select_related().filter(articles__supplier__in=("Supplier1","Supplier2")).filter(category_id__in=(413,678,699,736,770)).filter(articles__stock__gt=0).annotate(mp=Min("articles__price"))
这是 django 生成的 sql 查询:
SELECT `products`.`id`, `products`.`eans`, `products`.`model`,
`products`.`description`,`products`.`name`, `products`.`brand_id`,
`products`.`category_id`, `products`.`image`,
MIN(`articles`.`price`) AS `mp`,
FROM `products`
LEFT OUTER JOIN `articles` ON (`products`.`id` = `articles`.`product_id`)
INNER JOIN `categories` ON (`products`.`category_id` = `categories`.`id`)
INNER JOIN `articles` T4 ON (`products`.`id` = T4.`product_id`)
INNER JOIN `brands` ON (`products`.`brand_id` = `brands`.`id`)
WHERE (`articles`.`supplier` IN ("Supplier1", "Supplier2")
AND `products`.`category_id` IN (413, 678, 699, 736, 770)
AND T4.`stock` > 0 )
GROUP BY `products`.`id`, `products`.`id`, `products`.`eans`, `products`.`model`,
`products`.`description`, `products`.`name`, `products`.`brand_id`,
`products`.`category_id`, `products`.`image`
ORDER BY NULL
而且我什至没有得到那个价格的供应商名称!(我不知道如何获得它)。
以有效的方式做到这一点的最佳方法是什么?我觉得我错过了什么……