国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

django 按時間范圍查詢數(shù)據(jù)庫實(shí)例代碼

2020-02-22 23:15:04
字體:
供稿:網(wǎng)友

從前臺中獲得時間范圍,在django后臺處理request中數(shù)據(jù),完成format,按照范圍調(diào)用函數(shù)查詢數(shù)據(jù)庫。

介紹一個簡單的功能,就是從web表單里獲取用戶指定的時間范圍,然后在數(shù)據(jù)庫中查詢此時間范圍內(nèi)的數(shù)據(jù)。

數(shù)據(jù)庫里的model舉例是這樣:

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

假設(shè)我們從表單獲得的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里面的數(shù)據(jù)處理成datetime類型(這是django里響應(yīng)代碼的前半部分):

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作為端點(diǎn)篩選數(shù)據(jù)庫了,需要用到__range函數(shù),將上面代碼加上數(shù)據(jù)庫查詢動作:

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!" 

總結(jié)

以上就是本文關(guān)于django 按時間范圍查詢數(shù)據(jù)庫實(shí)例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 茂名市| 石河子市| 汶上县| 漠河县| 高要市| 桦川县| 长阳| 郧西县| 历史| 临安市| 汝城县| 遵义县| 通州区| 黑河市| 正镶白旗| 兴仁县| 巴林左旗| 张家川| 中西区| 东阳市| 庄河市| 北碚区| 余干县| 河北省| 渝中区| 驻马店市| 华池县| 云梦县| 安西县| 柘荣县| 禄丰县| 定州市| 五台县| 井陉县| 夏河县| 六盘水市| 获嘉县| 策勒县| 河源市| 阳城县| 崇阳县|