Django跨外键查询:获取需补货食材最多的TOP5供应商
没问题,我来帮你搞定这个Django查询需求!
解决Django查询:获取缺货食材最多的前五名供应商
首先我先假设你的模型关联逻辑大概是这样的(如果和实际有出入,你可以调整外键字段名):
Ingredients模型有一个外键字段(比如supplier)关联到Suppliers模型Ingredients包含stock_status字段,用来标记库存状态
接下来就是实现查询的核心代码:
from django.db.models import Count # 获取缺货食材最多的前五名供应商名称 top_suppliers = Suppliers.objects.filter( ingredients__stock_status="out of stock" ).annotate( out_of_stock_count=Count('ingredients') ).order_by( '-out_of_stock_count' )[:5].values_list('name', flat=True)
代码细节解释:
- 筛选缺货食材:用
filter(ingredients__stock_status="out of stock")通过反向关联筛选出有缺货食材的供应商,这里的ingredients是Suppliers模型对应的反向关联名称(如果你的外键设置了related_name,要换成对应的名称)。 - 统计缺货数量:
annotate(out_of_stock_count=Count('ingredients'))给每个供应商添加一个临时字段,统计其名下缺货食材的总数。 - 排序取前五:
order_by('-out_of_stock_count')按缺货数量降序排列,[:5]截取前五条数据,最后用values_list('name', flat=True)只提取供应商名称的列表。
如果你的模型关联是通过Restaurants中转的(比如Ingredients关联Restaurants,Restaurants关联Suppliers),那查询需要调整关联路径,同时避免重复计数:
top_suppliers = Suppliers.objects.filter( restaurants__ingredients__stock_status="out of stock" ).annotate( out_of_stock_count=Count('restaurants__ingredients', distinct=True) ).order_by( '-out_of_stock_count' )[:5].values_list('name', flat=True)
要是你需要获取完整的供应商对象而不仅仅是名称,去掉最后的values_list('name', flat=True)即可,这样就能访问供应商的其他字段了。
内容的提问来源于stack exchange,提问作者user4227817
相关产品推荐
相关产品推荐

