给定两个由不带直通表的ManyToMany连接的模型:
class Ingredient(models.Model):
name = models.CharField(max_length=255)
class Recipe(models.Model):
name = models.CharField(max_length=255)
ingredients = models.ManyToManyField(Ingredient)如何找到配方中正在使用的配料的实例总数?
例如,如果我有两种配料(苹果和糖)和两种食谱(苹果派和甜甜圈),我怎么知道食谱有三种用途(两种因为苹果派使用苹果和糖,一种因为甜甜圈使用糖)?
我可以使用以下命令来完成此操作:
count = 0
for recipe in Recipe.objects.all():
count += recipe.ingredients.count()但这会产生太多的查询。
有没有一种简单的方法可以通过注释/聚合来获得这个数字?
发布于 2019-05-31 23:55:58
我们可以像这样尝试(当然是为了避免大量的DB命中。使用数据库聚合)。
from django.db.models import Count
recipes = Recipe.objects.annotate(count_ingredients=Count('ingredients'))
for recipe in recipes:
print(recipe.pk, recipe.count_ingredients)发布于 2019-06-01 00:02:38
recipes = Recipe.objects.all()
for recipe in recipes:
print(recipe.ingredient_set.count())发布于 2019-06-01 00:08:20
Recipe.through.objects.filter(ingredient=YOUR_INGREDIENT_HERE).count()Recipe.through是保存many_to_many字段的对象的“秘密”表,一个新的Recipe_ingredients(django的默认名称)对象被创建。如果你想知道有多少食谱使用了给定的配料,你只需要用你的配料过滤这个表,并获得它的计数。
对于您的示例,将创建以下内容:(伪)
Recipe_ingredients(ingredient=sugar, recipe=apple_pie)
Recipe_ingredients(ingredient=sugar, recipe=doughnut)
Recipe_ingredients(ingredient=apple, recipe=apple_pie)从这里你可以用这个表计算任何东西,如果你想知道所有成分的总使用量,它就像这样简单
Recipe.through.objects.count()https://stackoverflow.com/questions/56398145
复制相似问题