时间筛选
如何使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。