ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

个人站点的日期查询

2019-02-17 09:53:24  阅读:241  来源: 互联网

标签:extra month 站点 日期 values time date 查询 select


˙一、知识储备

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'

 

 

 

标签:extra,month,站点,日期,values,time,date,查询,select
来源: https://www.cnblogs.com/lshedward/p/10390185.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有