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

yipeiwu_com5年前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 按时间范围查询数据库实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

使用wxpython实现的一个简单图片浏览器实例

上次我爬了n多图片,但是浏览的时候有一个问题。 图片浏览器的浏览一般都是按名称排的,而我对图片的命名是按照数字递增的。比如3总是会排在10后面,也就无法快速地浏览图片了。 所以,出于方便...

python 找出list中最大或者最小几个数的索引方法

如下所示: nums = [1,8,2,23,7,-4,18,23,24,37,2] result = map(nums.index, heapq.nlargest(3, nums)...

python算法演练_One Rule 算法(详解)

这样某一个特征只有0和1两种取值,数据集有三个类别。当取0的时候,假如类别A有20个这样的个体,类别B有60个这样的个体,类别C有20个这样的个体。所以,这个特征为0时,最有可能的是类别...

老生常谈进程线程协程那些事儿

老生常谈进程线程协程那些事儿

一、进程与线程 1.进程 我们电脑的应用程序,都是进程,假设我们用的电脑是单核的,cpu同时只能执行一个进程。当程序出于I/O阻塞的时候,CPU如果和程序一起等待,那就太浪费了,cpu会...

python操作MySQL数据库的方法分享

我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧: 复制代码 代码如下: import MySQLdb try: conn=MySQLdb.connect(host=...