2024-04-28 04:17:36 发布
网友
假设我有两个模型:
class Recipe(models.Model): recipe = models.TextField() ingredients = models.ManyToManyField(Ingredient) class Ingredient(models.Model): name = models.CharField()
我想知道所有的食谱中最常用的配料是什么。你知道吗
我该如何查询?你知道吗
阅读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
阅读https://docs.djangoproject.com/en/dev/topics/db/aggregation/上的聚合和注释
要获得最常见成分的名称:
相关问题 更多 >
编程相关推荐