按照月份归档

方法:

# django官网提供的一个orm语法
    from django.db.models.functions import TruncMonth
-官方提供
            from django.db.models.functions import TruncMonth
            Sales.objects
            .annotate(month=TruncMonth('timestamp'))  # Truncate to month and add to select list
            .values('month')  # Group By month
            .annotate(c=Count('id'))  # Select the count of the grouping
            .values('month', 'c')  # (might be redundant, haven't tested) select month and count
Sales就是models里面的模型类

示例:

# 按照年月统计所有的文章
    date_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values("month").annotate(count_num=Count("pk")).values_list('month','count_num')

# 先filter(blog=blog)查找到当前用户的所有文章
# annotate(month=TruncMonth('create_time')) 以创建时间的月分组
# 第二个annotate前的values("month")是分组条件
原文地址:https://www.cnblogs.com/baicai37/p/13096906.html