django 按時間范圍查詢數(shù)據(jù)庫實例代碼
從前臺中獲得時間范圍,在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?內(nèi)置模塊?argparse快速入門教程
argparse模塊是Python內(nèi)置的用于命令項選項與參數(shù)解析的模塊,argparse模塊可以讓人輕松編寫用戶友好的命令行接口,能夠幫助程序員為模型定義參數(shù),這篇文章主要介紹了快速入門Python內(nèi)置模塊argparse,需要的朋友可以參考下2023-06-06使用優(yōu)化器來提升Python程序的執(zhí)行效率的教程
這篇文章主要介紹了使用優(yōu)化器來提升Python程序的執(zhí)行效率的教程,包括編寫計時器和使用內(nèi)建的優(yōu)化器等,需要的朋友可以參考下2015-04-04python的ping網(wǎng)絡(luò)狀態(tài)監(jiān)測的實現(xiàn)(含多IP)
本文主要介紹了python的ping網(wǎng)絡(luò)狀態(tài)監(jiān)測的實現(xiàn)(含多IP),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03python利用高階函數(shù)實現(xiàn)剪枝函數(shù)
這篇文章主要為大家詳細(xì)介紹了python利用高階函數(shù)實現(xiàn)剪枝函數(shù)的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03國產(chǎn)化設(shè)備鯤鵬CentOS7上源碼安裝Python3.7的過程詳解
這篇文章主要介紹了國產(chǎn)化設(shè)備鯤鵬CentOS7上源碼安裝Python3.7,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05