繁体   English   中英

如何向后检索ManyToMany关系中的对象数

[英]How to retrieve the number of objects in a ManyToMany relationship backwards

我有两个模型:

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的列表?

那不是您使用annotate 它应该是:

Tag.objects.annotate(prod_num=Count('product')).order_by('prod_num')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM