【发布时间】:2019-05-31 15:45:51
【问题描述】:
给定两个由 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)
如何找到配方中使用的某种成分的实例总数?
例如,如果我有两种配料(苹果和糖)和两种食谱(苹果派和甜甜圈),我怎么知道食谱有 3 种用途(两种因为苹果派使用苹果和糖,一种因为甜甜圈用糖)?
我可以通过以下方式做到这一点:
count = 0
for recipe in Recipe.objects.all():
count += recipe.ingredients.count()
但这会产生太多查询。
有没有一种简单的方法可以通过注释/聚合获得这个数字?
【问题讨论】:
标签: django django-models