0
我有两个表,分别叫做Image
和Product
。在django查询中混合注释和聚合
class Image():
product = Foreignkey(Product, related_name='image')
#some more field e.g. image_name, slug, caption, etc.
产品可以有零,一个或最多5个图像。 我想计算X号产品的数量。的图像。
我试着用朴素的方法,但它做N(#products)+1 SQL查询。
d = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
for x in product.objects.all():
d[x.image.count()] += 1
我认为我们可以用select_related
但不知道如何做到这一点做到这一点。 我试着做批注但不工作。 Image.objects.annotate(x=Count('product'))
我对django的经验并不多。我想知道如果我可以用单个查询或更优化的方式来做到这一点。