您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)django中怎么按時(shí)間范圍查詢數(shù)據(jù)庫(kù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
數(shù)據(jù)庫(kù)里的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里面的時(shí)間范圍最初是這樣的:
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!"
接下來(lái)就可以用獲得的 date_from
和date_to
作為端點(diǎn)篩選數(shù)據(jù)庫(kù)了,需要用到__range
函數(shù),將上面代碼加上數(shù)據(jù)庫(kù)查詢動(dò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) book_list = book.objects.filter(date__range=(date_from, date_to)) print book_list else: print "error time range!"
看完上述內(nèi)容,你們對(duì)django中怎么按時(shí)間范圍查詢數(shù)據(jù)庫(kù)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。