Django如何按多对多事件排序

2024-04-28 04:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个模型:

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

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

我想知道所有的食谱中最常用的配料是什么。你知道吗

我该如何查询?你知道吗


Tags: name模型modelmodelsrecipeclasstextfieldcharfield
1条回答
网友
1楼 · 发布于 2024-04-28 04:17:36

阅读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

相关问题 更多 >