• 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
    

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

  • 相关阅读:
    celery 转自:https://www.cnblogs.com/pyedu/p/12461819.html
    k8s 学习笔记
    linux 学习笔记3
    yaml initc
    vi 块操作
    curl
    知名IT互联网公司
    ajax 上传文件给webapi(带basic认证)
    C# 后台请求api
    mvc 母版页保持不刷新
  • 原文地址:https://www.cnblogs.com/cnhyk/p/12274347.html
Copyright © 2020-2023  润新知