python - 我如何在这里使用 ModelName.objects.aggregate(Sum('field_name')) ?
问题描述
我需要使用Sum()
而不是
if name in ingredients.keys():
ingredients[name] += units
else:
ingredients[name] = units
但我不知道怎么做,因为我有很长的关系链。这是我的代码:
def shopping_list_ingredients(request):
shopping_list = ShoppingList.objects.filter(user=request.user).all()
ingredients = {}
for item in shopping_list:
for x in item.recipe.recipe_ingredient.all():
name = f'{x.ingredient.title} ({x.ingredient.unit})'
units = x.count
if name in ingredients:
ingredients[name] += units
else:
ingredients[name] = units
download = []
for key, units in ingredients.items():
download.append(f'{key} - {units} \n')
return download
解决方案
def shopping_list_ingredients(request):
shopping_list = ShoppingList.objects.filter(user=request.user).all()
ingredients = {}
for item in shopping_list:
#if item.recipe.recipe_ingredient.all().ingredient.unit is dict
values = item.recipe.recipe_ingredient.all().ingredient.unit.values()
total = sum(values)
#if it's list
total = sum(item.recipe.recipe_ingredient.all().ingredient.unit)
推荐阅读
- java - JFoenix TabPane 选项卡标签颜色
- sql-server - 如何使用 SQL Server Management Studio 2017 调试 T-SQL?
- r - 如何计算忽略NA的每列的平均值
- json - 如何将 json 属性展平为 _source 使用的 ELK?
- r - 根据数据框中另一列中的条件对列求和
- performance - 了解分支预测效率
- android - 更改片段时 UI 中断
- c# - 调用返回值的数据库存储函数或存储过程
- javascript - Material UI 组件不返回 HTMLElement 引用
- java - 我如何使用 onUpgrade 方法?