使用方法
將原來字段的日期年月日按照月份截取成一個新的虛擬字段以供使用。
-官方提供
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
如果沒有報錯,無需進行上述操作,無需修改時間。