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

如果沒有報錯,無需進行上述操作,無需修改時間。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM