Django如何按很多次发生排序

时间:2012-07-04 15:48:43

标签: python django

假设我有2个型号:

class Recipe(models.Model):
    recipe = models.TextField()
    ingredients = models.ManyToManyField(Ingredient)

class Ingredient(models.Model):
    name = models.CharField()

我想知道所有食谱中使用最多的成分。

如何查询?

1 个答案:

答案 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
相关问题