django 按時間范圍查詢數(shù)據(jù)庫實(shí)例代碼
從前臺中獲得時間范圍,在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)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
Python報錯SyntaxError:unexpected?EOF?while?parsing的解決辦法
在運(yùn)行或編寫一個程序時常會遇到錯誤異常,這時python會給你一個錯誤提示類名,告訴出現(xiàn)了什么樣的問題,下面這篇文章主要給大家介紹了關(guān)于Python報錯SyntaxError:unexpected?EOF?while?parsing的解決辦法,需要的朋友可以參考下2022-07-07
利用Python和PyQt5構(gòu)建一個多功能PDF轉(zhuǎn)換器
在日常工作中,處理PDF文件幾乎是每個人都不可避免的任務(wù),本文將通過Python和PyQt5搭建一個強(qiáng)大的PDF文件處理平臺,希望對大家有所幫助2024-12-12

