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

首頁 > 編程 > Python > 正文

詳解Django通用視圖中的函數(shù)包裝

2020-02-23 01:40:20
字體:
供稿:網(wǎng)友

用函數(shù)包裝來處理復(fù)雜的數(shù)據(jù)過濾

另一個(gè)常見的需求是按URL里的關(guān)鍵字來過濾數(shù)據(jù)對象。 之前,我們在URLconf中硬編碼了出版商的名字,但是如果我們想用一個(gè)視圖就顯示某個(gè)任意指定的出版商的所有書籍,那該怎么辦呢? 我們可以通過對 object_list 通用視圖進(jìn)行包裝來避免 寫一大堆的手工代碼。 按慣例,我們先從寫URL配置開始:

urlpatterns = patterns('', (r'^publishers/$', list_detail.object_list, publisher_info), **(r'^books/(/w+)/$', books_by_publisher),**)

接下來,我們寫 books_by_publisher 這個(gè)視圖:

from django.shortcuts import get_object_or_404from django.views.generic import list_detailfrom mysite.books.models import Book, Publisherdef books_by_publisher(request, name): # Look up the publisher (and raise a 404 if it can't be found). publisher = get_object_or_404(Publisher, name__iexact=name) # Use the object_list view for the heavy lifting. return list_detail.object_list(  request,  queryset = Book.objects.filter(publisher=publisher),  template_name = 'books/books_by_publisher.html',  template_object_name = 'book',  extra_context = {'publisher': publisher} )

這樣寫沒問題,因?yàn)橥ㄓ靡晥D就是Python函數(shù)。 和其他的視圖函數(shù)一樣,通用視圖也是接受一些 參數(shù)并返回 HttpResponse 對象。 因此,通過包裝通用視圖函數(shù)可以做更多的事。

注意

注意在前面這個(gè)例子中我們在 extra_context中傳遞了當(dāng)前出版商這個(gè)參數(shù)。
處理額外工作

我們再來看看最后一個(gè)常用模式:

想象一下我們在 Author 對象里有一個(gè) last_accessed 字段,我們用這個(gè)字段來記錄最近一次對author的訪問。 當(dāng)然通用視圖 object_detail 并不能處理這個(gè)問題,但是我們?nèi)匀豢梢院苋菀椎鼐帉懸粋€(gè)自定義的視圖來更新這個(gè)字段。

首先,我們需要在URL配置里設(shè)置指向到新的自定義視圖:

from mysite.books.views import author_detailurlpatterns = patterns('', # ... **(r'^authors/(?P<author_id>/d+)/$', author_detail),** # ...)

接下來寫包裝函數(shù):

import datetimefrom django.shortcuts import get_object_or_404from django.views.generic import list_detailfrom mysite.books.models import Authordef author_detail(request, author_id): # Delegate to the generic view and get an HttpResponse. response = list_detail.object_detail(  request,  queryset = Author.objects.all(),  object_id = author_id, ) # Record the last accessed date. We do this *after* the call # to object_detail(), not before it, so that this won't be called # unless the Author actually exists. (If the author doesn't exist, # object_detail() will raise Http404, and we won't reach this point.) now = datetime.datetime.now() Author.objects.filter(id=author_id).update(last_accessed=now) return response            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 盐城市| 客服| 边坝县| 仁怀市| 拉孜县| 盐山县| 金湖县| 班玛县| 广宗县| 乐陵市| 上犹县| 公安县| 唐河县| 绥芬河市| 吉隆县| 西宁市| 尤溪县| 深泽县| 广平县| 清新县| 洪泽县| 柘城县| 定兴县| 江达县| 迁安市| 汽车| 兰溪市| 饶平县| 荆门市| 玉山县| 汝南县| 华宁县| 绥江县| 湛江市| 高要市| 锦屏县| 邢台县| 北京市| 时尚| 介休市| 海安县|