个人站点的日期查询

˙一、知识储备

mysql可以通过date_format格式化时间格式

create table t_mul_new(d date,t time,dt datetime);

# date:年月日

# time:时分秒

# datetime:年月日时分秒

# 只取年和月

select date_format(dt,"%Y-%m") from t_mul_new;

# 取年月日

select date_format(dt,"%Y-%m-%d") from t_mul_new;

 

二、日期归档查询方式1

extra

extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)

有些情况下,Django的查询语法难以简单的表达复杂的 WHERE 子句,对于这种情况, Django 提供了 extra() QuerySet修改机制 — 它能在 QuerySet生成的SQL从句中注入新子句

extra可以指定一个或多个 参数,例如 select, where or tables. 这些参数都不是必须的,但是你至少要使用一个!要注意这些额外的方式对不同的数据库引擎可能存在移植性问题.(因为你在显式的书写SQL语句),除非万不得已,尽量避免这样做。

 

参数之select

select 参数可以让你在 SELECT 从句中添加其他字段信息,它应该是一个字典,存放着属性名到 SQL 从句的映射。

queryResult=models.Article.objects.extra(select={'is_recent': "create_time > '2017-09-05'"}) 结果集中每个 Entry 对象都有一个额外的属性is_recent, 它是一个布尔值,表示 Article对象的create_time 是否晚于2017-09-05.

 # <QuerySet [{'is_recent': 1, 'title': '利用浏览器事件免费谷歌翻译(Google Translate)'},.....

如果改成2018-09-05,那么is_recent就都是0了

格式化时间

article_obj=models.Article.objects.extra(select={"standard_time":"strftime('%%Y-%%m-%%d',create_time)"}).values("standard_time","nid","title")
       
print(article_obj)
 models.Article.objects.filter(user=user).extra(
        select={'y_m_date': "date_format(created_time,'%%Y-%%m')"}).values(
        'y_m_date').annotate(
        count=Count('nid')).values('y_m_date', 'count')
    print(date_list)  # <QuerySet [{'y_m_date': '2019-02', 'count': 2}]>

 

三、日期归档查询方式2

借助django提供的库

from django.db.models.functions import TruncMonth

Sales.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   

models.Article.objects.filter(user=user).annotate(month=TruncMonth('created_time')).values('month').annotate(
        count=Count('nid')).values_list(
        'month', 'count'

猜你喜欢

转载自www.cnblogs.com/lshedward/p/10390185.html
今日推荐