我有两种模式:
class Tag(models.Model):
""" This class rapresent a tag that can be applied to a product's
category """
name = models.SlugField()
class Product(models.Model):
""" This class rapresent a product """
product_id = models.IntegerField()
image = models.ImageField(max_length=1024)
price = models.DecimalField(max_digits=6, decimal_places=2)
discount = models.DecimalField(max_digits=6, decimal_places=2)
brand = models.CharField(max_length=200, default='')
category = models.ManyToManyField(Tag)
gender = models.CharField(max_length=200, default='')
last_updated = models.DateTimeField(auto_now=False, auto_now_add=False,
default=timezone.now)
我无法弄清楚如何检索与每个标记对象绑定的产品数量。我尝试过类似的东西:
Tag.objects.annotate(prod_num=Count(Tag.product_set.all())).order_by('prod_num')
但似乎无法正常工作。有一种很好的方法来获取tag_name,num_of_prods?
的列表答案 0 :(得分:3)
这不是你使用annotate
的方式。它应该是:
Tag.objects.annotate(prod_num=Count('product')).order_by('prod_num')