views.py

我們在urls.py中寫的轉(zhuǎn)發(fā)方法,都需要有參數(shù)request
request包含了所有用戶請求的信息。

def news(request):
    return render(request, 'news.html')

request

我們在urls.py中的方法的參數(shù)request,包含了請求頭所有的信息。

1)request.method
請求方式:GET/POST

2)request.POST 和 request.GET
這里的POST或者GET相當(dāng)于對應(yīng)方式提交過來的封裝好的字典。

request.POST['username']
request.POST['password']

跨表查詢:

<ul>
    {% for row in  hosts%}
    <li>{{row.nid}} - {{row.hostname}} - {{row.ip}} - {{row.port}} - {{row.bussiness.id}} - {{row.bussiness_id}}</li>
    {% endfor %}
</ul>

bussiness_id是一個外鍵,bussiness_id與bussiness.id的值是一樣的,但是它們有一些不一樣的地方,那就是bussiness.id經(jīng)過了跨表查詢,而bussiness_id在表中直接有。


三種查詢結(jié)果的方式:
1)直接

models.Host.objects.filter(id=1)

2)values,獲得字典為基礎(chǔ)的QuerySet

models.Host.objects.all().values('id', 'hostname', 'port')

3)value_list,以元組為基礎(chǔ)的QuerySet

models.Host.objects.all().value_list('id', 'hostname', 'port')

values跨表查詢

雙下劃線(__)的作用:

v2 = models.Host.objects.filter(id=1).values('id', 'hostname', 'business_id', 'business__caption')

注意:這里必須是雙下劃線(__),而不能是點(.


經(jīng)驗:

1.上一頁,下一頁,查詢優(yōu)化:

def productdetails(request, nid):

    data = getData()

    wine_one = models.Winery.objects.filter(id=nid).first()
    wine_first = models.Winery.objects.all().first()
    wine_last = models.Winery.objects.all().last()

    if nid <= wine_first.id:
        nid = 1
    elif nid > wine_last.id:
        nid = wine_last.id 

    temp_id = nid

    while wine_one == None:

        temp_id = temp_id + 1

        wine_one = models.Winery.objects.filter(id=str(temp_id)).first()
        if temp_id > wine_last.id:
            wine_one = wine_first
            break

    data['wine_one'] = wine_one

    print (data['wine_one'].title)  # there ouput the "gaoliangjiu"

    return render(request, 'article_list_content.html', {'data':data})

2.請求:

views.py:

def detail(request, id):
    article = get_object_or_404(Article, pk=id)
    return render(request, "page/detail.html", context)

3.查詢的時候filter刪選,可以傳入字典

dict = {'article_type_id':1, 'category_id':2}
result = models.Article.objects.filter()

request請求內(nèi)容。

圖片.png

給響應(yīng)頭添加數(shù)據(jù)


給響應(yīng)頭添加數(shù)據(jù).png

4.在views.py的def方法中:

def test(request):
    print(type(request))
    return HttpResponse("<p>test ok!</p>")

請求來的request是WSGIRequest:
<class 'django.core.handlers.wsgi.WSGIRequest'>
返回的是HttpResponse

5.try...except...else...finally

try:
     Normal execution block
except A:
     Exception A handle
except B:
     Exception B handle
except:
     Other exception handle
else:
     if no exception,get here
finally:
     print("finally")   

下面的代碼的執(zhí)行可以確定queryset是懶加載,可以先保存,然后再?。?/p>

def favorite(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    try:
        selected_song = album.song_set.get(pk=request.POST['song'])
    except (KeyError, Song.DoesNotExist):
        return  render(request, 'music/detail.html', {
            "album":album,
            "error_message":"You did not select a valid song",
        })
    else:
        selected_song.is_favorite = True
        selected_song.save()
        return render(request, 'music/detail.html', {
            "album":album,
        })

generic views

示例:

from django.views import generic

class IndexView(generic.ListView):
    template_name = 'music/index.html'
    context_object_name = 'album_list'  # 注意:默認的是objects_list
    
    def get_queryset(self):
        return Album.objects.all()   # 注意:默認的是objects_list

CreateView,UpdateView,DeleteView:

from django.views.generic.edit import CreateView,UpdateView,DeleteView
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容