简体   繁体   中英

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

I have two models:

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)

I can't figure out how to retrieve the number of products that are bounded with every tag object. I've tried something like:

Tag.objects.annotate(prod_num=Count(Tag.product_set.all())).order_by('prod_num')

but it seems that nothing works properly. There is a nice and clean way to obtain a list of tag_name, num_of_prods?

That's not how you use annotate . It should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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