以下代码可以帮助我使用List Comprehension吗?

时间:2018-06-04 12:08:30

标签: python-3.x list list-comprehension

total_login=Queryset
this_month = datetime.now().month
this_month_login = 0
last_month_login = 0
second_last_month_login = 0
if total_login:
    for i in total_login:
        if i.created_at.month==this_month:
            this_month_login+=1
        if i.created_at.month==this_month-1:
            last_month_login+=1
        if i.created_at.month==this_month-2:
            second_last_month_login+=1

另外,如果我想自动化数月的数据,我们将如何做到这一点?就像说n个月而不是仅仅过去两个月。

1 个答案:

答案 0 :(得分:0)

您可以尝试按月对每个项目进行分组并计算它们。像这样:

Queryset.objects.all().values_list('created_at__month').annotate(total_item=Count('id'))

然后处理结果并提取您需要的月份。