Django 时间筛选

时间筛选

  如何使用ORM筛选出某一时间段中的数据?

  例如博客园中的这种格式:

2020年9月(32)
2020年8月(30)
2020年6月(4)

操作演示

  如下,我们有这样一张数据表:

from django.db import models

# Create your models here.
class Article(models.Model):
    article_name = models.CharField(max_length=32,verbose_name="书名")
    create_time = models.DateField(auto_now=False, auto_now_add=False)

    def __str__(self):
        return "对象-%s"%article_name
        

  为他插入一些内容,这里就直接navicat插入了。

image-20200923001508204

  这是官方提供的方法:

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

 

  按着它的写

from django.shortcuts import render
from django.db.models.functions import TruncMonth
from django.db.models import Count
from app01 import models

# Create your views here.
def test(request):
    # 取别名
    data = models.Article.objects.annotate(month=TruncMonth("create_time")).values('month').annotate(num=Count("pk")).values_list("month","num") # 拿月份和数量
    print(data)
    
    return render(request,"test.html",locals())

  页面上这样渲染即可:

<body>
    {% for row in data  %}
    <p>{{row.0|date:"Y年m月"}}({{row.1}})</p>
    {% endfor %}
</body>

image-20200923002933589

注意事项

  如果使用过程中有问题,则需要修改一下时区。

  在settings.py中进行如下设置:

TIME_ZONE = "Asia/Shanghai"
USE_TZ = False
posted @ 2020-09-23 00:35  云崖先生  阅读(431)  评论(0编辑  收藏  举报