[英]How to get a count of a value in a ManyToMany field
I have a model called Recipe that is simplified to have a title and category.我有一个名为 Recipe 的 model,它被简化为具有标题和类别。 The category is a ManyToMany field.该类别是一个多对多字段。
class Recipe(models.Model):
title = models.CharField(max_length=100)
category = models.ManyToManyField(Category, help_text='Select a category')
I have another model called Category我还有另一个 model 叫做 Category
class Category(models.Model):
name = models.CharField(max_length=200, help_text='Enter a baking category')
def __str__(self):
return self.name
There are several categories but for simplicity, let's say we have two: Bread and Cake.有几个类别,但为简单起见,假设我们有两个:面包和蛋糕。 How would I query the DB to figure out how many Recipes I have of each category?我将如何查询数据库以找出每个类别有多少食谱?
I've been trying something like this:我一直在尝试这样的事情:
total_bread= Recipe.objects.filter(categories=1).annotate(category_count=Count('Bread'))
But that isn't working.但这行不通。 I also don't want to explicitly define all the categories I'm looking for since in the future I would add more categories.我也不想明确定义我正在寻找的所有类别,因为将来我会添加更多类别。
Since you want the count of how many recipes there are for each Category
you should annotate on it instead of on Recipe
:由于您想要计算每个Category
有多少食谱,您应该在其上而不是在Recipe
上进行注释:
categories = Category.objects.annotate(recipe_count=Count('recipe'))
for category in categories:
print(category.name, category.recipe_count)
# For particular category:
bread = Category.objects.annotate(recipe_count=Count('recipe')).get(name='Bread')
print(bread.recipe_count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.