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

首頁 > 編程 > Python > 正文

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

2020-01-04 15:51:55
字體:
供稿:網(wǎng)友

從前臺中獲得時間范圍,在python/283970.html">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作為端點篩選數(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ù)庫實例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 玉环县| 武乡县| 仁怀市| 子洲县| 汪清县| 新巴尔虎右旗| 扬州市| 济阳县| 平江县| 如东县| 虹口区| 棋牌| 象山县| 清丰县| 额敏县| 响水县| 纳雍县| 麟游县| 天水市| 刚察县| 兴义市| 河西区| 进贤县| 平谷区| 阿拉善右旗| 五指山市| 林口县| 德清县| 紫云| 宁远县| 乐平市| 武胜县| 孝义市| 丰宁| 塔城市| 金沙县| 册亨县| 凤冈县| 东莞市| 铁岭市| 中阳县|