Django:从 dict 查询集中添加值

问题描述 投票:0回答:1

我有这个条目监控表,其中有多个日期和时间值。我想获得每个月的条目总数,每个用户每天都有多个条目。

我用了这条线:

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,我应该如何分离该值?因为我会按月为这个总值制作一个图表。

python django
1个回答
0
投票

看看你的问题,我相信你想要的是在你的 ListView 的查询集中增加每月计数统计数据的总累计值 - 1 + 25 = 26 ?

这是您的代码的更新版本,以及如何通过我写的注释来实现这一目标,以便您清楚地理解我。


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


注意:如果您不熟悉 Django 基于类的视图,请查看此处的文档。祝你好运,伙计。

© www.soinside.com 2019 - 2024. All rights reserved.