首页 > 解决方案 > 我如何在这里使用 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

标签: python

解决方案


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)
    

推荐阅读