假设我有2个型号:
class Recipe(models.Model):
recipe = models.TextField()
ingredients = models.ManyToManyField(Ingredient)
class Ingredient(models.Model):
name = models.CharField()
我想知道所有食谱中使用最多的成分。
如何查询?
答案 0 :(得分:2)
了解https://docs.djangoproject.com/en/dev/topics/db/aggregation/
的汇总和注释获取最常见成分的名称:
from django.db.models import Count
most_common = Ingredient.objects.annotate(num_recipes=Count('recipe')).order_by('-num_recipes')[0]
print most_common.name