django 按时间范围查询数据库实例代码

yipeiwu_com6年前Python基础

从前台中获得时间范围,在django后台处理request中数据,完成format,按照范围调用函数查询数据库。

介绍一个简单的功能,就是从web表单里获取用户指定的时间范围,然后在数据库中查询此时间范围内的数据。

数据库里的model举例是这样:

class book(models.Model):  
  name = models.CharField(max_length=50, unique=True) 
  date = models.DateTimeField() 
    
  def __unicode__(self): return self.name 

假设我们从表单获得的request.GET里面的时间范围最初是这样的:

request.GET = {'year_from': 2010, 'month_from': 1, 'day_from': 1, 
        'year_to':2013, 'month_to': 10, 'day_to': 1}

由于model里保存的date类型是models.DateTimefield() ,我们需要先把request里面的数据处理成datetime类型(这是django里响应代码的前半部分):

import datetime 
 
def filter(request): 
  if 'year_from' and 'month_from' and 'day_from' and\ 
      'year_to' and 'month_to' and 'day_to' in request.GET: 
    y = request.GET['year_from'] 
    m = request.GET['month_from'] 
    d = request.GET['day_from'] 
    date_from = datetime.datetime(int(y), int(m), int(d), 0, 0) 
    y = request.GET['year_to'] 
    m = request.GET['month_to'] 
    d = request.GET['day_to'] 
    date_to = datetime.datetime(int(y), int(m), int(d), 0, 0) 
  else: 
    print "error time range!" 

接下来就可以用获得的 date_from date_to作为端点筛选数据库了,需要用到__range函数,将上面代码加上数据库查询动作:

import datetime 
 
def filter(request): 
  if 'year_from' and 'month_from' and 'day_from' and\ 
      'year_to' and 'month_to' and 'day_to' in request.GET: 
    y = request.GET['year_from'] 
    m = request.GET['month_from'] 
    d = request.GET['day_from'] 
    date_from = datetime.datetime(int(y), int(m), int(d), 0, 0) 
    y = request.GET['year_to'] 
    m = request.GET['month_to'] 
    d = request.GET['day_to'] 
    date_to = datetime.datetime(int(y), int(m), int(d), 0, 0) 
    book_list = book.objects.filter(date__range=(date_from, date_to)) 
    print book_list 
  else: 
    print "error time range!" 

总结

以上就是本文关于django 按时间范围查询数据库实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python matplotlib画图与中文设置操作实例分析

Python matplotlib画图与中文设置操作实例分析

本文实例讲述了Python matplotlib画图与中文设置操作。分享给大家供大家参考,具体如下: 采用matplotlib作图时默认设置下是无法显示中文的,例如编写如下python脚...

将Python中的数据存储到系统本地的简单方法

有很多时候,我们会在python的运行过程中得到一些重要的变量,比如一个数据量很庞大的dict。而且,后面的某些程序也会用到这个dict,那么我们就最好把它存储到本地来,然后下次调用的时...

python获取当前运行函数名称的方法实例代码

python获取当前运行函数名称的方法实例代码 摘要: c/c++中获取函数所在源码名,函数名和行号的方法很简单 __FILE__,__FUNCTION__和__LINE__ pytho...

Python合并多个装饰器小技巧

django程序,需要写很多api,每个函数都需要几个装饰器,例如 复制代码 代码如下: @csrf_exempt  @require_POST  def&nbs...

Python OpenCV之图片缩放的实现(cv2.resize)

Python OpenCV之图片缩放的实现(cv2.resize)

OpenCV函数原型: cv2.resize(InputArray src, OutputArray dst, Size, fx, fy, interpolation) 参数解释:...