Django: Добавление значений из dict Queryset

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

Я использовал эту строку:

stats=EntryMonitoring.objects.filter(student_id=user).annotate(month=TruncMonth('date')).values('month').annotate(total=Count('id'))

Результаты:

<QuerySet [{'month': datetime.date(2024, 3, 1), 'total': 25}, {'month': datetime.date(2024, 4, 1), 'total': 1}]>

Я просматриваю данные с помощью этого {% for obj in stats %}{{ obj.total }}{% endfor %}. Таким образом, я получил 251. Я хочу сложить итоговые значения, например 25 и 1, чтобы в сумме получилось 26 записей за год. А для 251, как я должен разделить значения? Потому что я буду строить график для этих суммарных значений по месяцам.

Посмотрев на ваш вопрос, я полагаю, что вы хотите увеличить общую кумулятивную статистику ежемесячных подсчетов правильно - 1 + 25 = 26 в вашем наборе запросов ListView?

Вот обновленная версия вашего кода, и как вы можете достичь этого мата с комментариями, которые я написал, чтобы вы поняли меня ясно.


import datetime
from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.views import generic

# since I didn't see your view, I assume you are using the View class
# However, you can replace this view name with your own name

class MonthlyStatListView(generic.ListView):

    template_name = 'your template url here'
    ordering = 'id'
    context_name = "if any, write your context name"


    def get_queryset(self):

        # your code
        queryset = EntryMonitoring.objects.filter(student_id=user).\
                       annotate(month=TruncMonth('date')).values('month').\
                       annotate(total=Count(self.ordering)) 

        # assumed results - and your goal is to add up the cummulative total in each month
        stats = [
                {'month': datetime.date(2024, 3, 1), 'total': 
            25}, 
               {'month': datetime.date(2024, 4, 1), 'total': 
              1}
                
                ]

        cumulative_total = 0

        #Iterate through the list of dictionaries in order via forloop
        for entry in  queryset[::1]:
            # add the ‘total’ value to the cumulative total for each dictionary, 
            cumulative_total += entry['total']

            #  updated list of dictionaries of the entry
            entry['cumulative_total'] = cumulative_total

        print(queryset)
        # the print statement will return this below as your answer, which you can now use on your template

        # [{'month': datetime.date(2024, 3, 1), 'total': 25, 'cumulative_total': 25}, {'month': datetime.date(2024, 4, 1), 'total': 1, 'cumulative_total': 26}]

        return queryset


NB: Если вы не знакомы с Django Class-Based Views, любезно ознакомьтесь с ним здесь в документации. Удачи, приятель.

Вернуться на верх