时间筛选
如何使用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插入了。

这是官方提供的方法:
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>

注意事项
如果使用过程中有问题,则需要修改一下时区。
在settings.py 中进行如下设置:
TIME_ZONE = "Asia/Shanghai"
USE_TZ = False
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|