Django之TruncMonth截取日期作为新的虚拟字段使用

使用方法

将原来字段的日期年月日按照月份截取成一个新的虚拟字段以供使用。

-官方提供
from django.db.models.functions import TruncMonth
Article.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

示例代码:

# 后端代码
date_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values('month').annotate(c=Count('pk')).values('c', 'month')
<!--前端解析代码-->
{% for date in date_list %}
    <p><a href="#">{{ date.month|date:'Y-m' }}({{ date.c }})</a></p>
{% endfor %}

时区报错问题

当在使用的过程中发现报错,但是代码没有问题,可能是时区的问题(内部使用的是UTC时间),在settings中加入以下两条:

TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False

如果没有报错,无需进行上述操作,无需修改时间。

原文地址:https://www.cnblogs.com/cnhyk/p/12274347.html