從前臺中獲得時間范圍,在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!"
以上就是本文關(guān)于django 按時間范圍查詢數(shù)據(jù)庫實(shí)例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選