• 欢迎访问V小白网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入V小白 暂无QQ群
  • 欢迎访问V小白网站,这是第二个滚动条

views.py

其他分类 admin 2019年6月27日 10:46 74 0 个评论

request

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

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

跨表查询:

三种查询结果的方式:
1)直接

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

3)value_list,以元组为基础的QuerySet

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

双下划线(__)的作用:


经验:

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.请求:

3.查询的时候filter删选,可以传入字典

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

给响应头添加数据 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")   

下面的代码的执行可以确定queryset是懒加载,可以先保存,然后再取:

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

V小白 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:views.py
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到
0个小伙伴在吐槽