Python 如何反向检索多个关系中的对象数
我有两种型号:Python 如何反向检索多个关系中的对象数,python,django,database,Python,Django,Database,我有两种型号: 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 = mode
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.objects.annotate(prod_num=Count('product')).order_by('prod_num')
这不是使用注释的方式。应该是:
Tag.objects.annotate(prod_num=Count('product')).order_by('prod_num')
prod\u num
从何而来?在文档中,它说,num.*
这只是一个新名称,您正在用它注释查询集中的每个对象。因此,您可以使用num.*
或*\num
。我认为他们在文档中使用的是num.*
,因为它可读性和可理解性。prod\u num
来自哪里?在文档中,它说,num.*
这只是一个新名称,您正在用它注释查询集中的每个对象。因此,您可以使用num.*
或*\num
。我认为他们在文档中使用的是num.*
,因为它可读性强,易于理解。