按照月份归档

方法:

# 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")是分组条件

 注意1:模块下还有好多Trunc..方法

 注意2:

如果按照上述写法上出现报错,那么需要去settings.py配置文件中修改时区

https://www.cnblogs.com/baicai37/p/13050234.html

posted @ 2020-06-11 23:52  耗油炒白菜  阅读(228)  评论(0)    收藏  举报