Объединение двух отфильтрованных объектов позволяет получить один объект данных

У меня есть два отфильтрованных объекта, основанных на месяцах в году. Я хотел бы вернуть один объект, основанный на тех же месяцах, но с разными суммированными значениями. Я придумал, как это можно сделать, и на данный момент у меня есть готовая установка. Я намерен кэшировать результат и обновлять его при любых изменениях в базе данных. Я просто не могу отделаться от ощущения, что может быть лучший способ сделать это.

@permission_classes([IsAuthenticated])
@api_view(["GET"])
def refBonus(request):
    user = request.user
    referralBonus = AddToWallet.objects.filter(user=user,
                                               type="Referral").annotate(month=TruncMonth('date')
                                                                         ).values('month').annotate(Sum('amount'))
    aggregatedProfit = Profit.objects.filter(user=user).annotate(month=TruncMonth('date')).values(
        'month').annotate(Sum('amount'))
    newList = []
    for i in aggregatedProfit:
        for e in referralBonus:
            if i["month"] == e["month"]:
                h = {'month': i["month"], "profit": i["amount__sum"], "bonus": e["amount__sum"]}
                newList.append(h)
    months = []
    for i in newList:
        # Append all months in newList to months variable
        months.append(i["month"])
    # Check if a month present in aggregatedProfit is not present in months already, add it to the months variable along
    # with bonus being 0 as it means bonus does have data for that month
    for i in aggregatedProfit:
        if i["month"] not in months:
            h = {'month': i["month"], "profit": i["amount__sum"], "bonus": 0}
            months.append(i["month"])  # Append the month the months variable
            newList.append(h)
    # Check if a month present in referralBonus is not present in months already, add it to the months variable along
    # with bonus being 0 as it means profit does have data for that month
    for i in referralBonus:
        if i["month"] not in months:
            h = {'month': i["month"], "profit": 0, "bonus": i["amount__sum"]}
            newList.append(h)
    newList = sorted(newList, key=lambda d: d['month'])  # Sort based on the month
    return Response(newList)
Вернуться на верх