我们在urls.py中写的转发方法,都需要有参数request
request
包含了所有用户请求的信息。
def news(request):
return render(request, 'news.html')
request
我们在urls.py中的方法的参数request
,包含了请求头所有的信息。
1)request.method
请求方式:GET/POST
2)request.POST 和 request.GET
这里的POST或者GET相当于对应方式提交过来的封装好的字典。
request.POST['username']
request.POST['password']
跨表查询:
{% for row in hosts%}
- {{row.nid}} - {{row.hostname}} - {{row.ip}} - {{row.port}} - {{row.bussiness.id}} - {{row.bussiness_id}}
{% endfor %}
bussiness_id是一个外键,bussiness_id与bussiness.id的值是一样的,但是它们有一些不一样的地方,那就是bussiness.id经过了跨表查询,而bussiness_id在表中直接有。
三种查询结果的方式:
1)直接
models.Host.objects.filter(id=1)
2)values,获得字典为基础的QuerySet
models.Host.objects.all().values('id', 'hostname', 'port')
3)value_list,以元组为基础的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')
注意:这里必须是双下划线(__
),而不能是点(.
)
经验:
1.上一页,下一页,查询优化:
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请求内容。
给响应头添加数据
4.在views.py的def方法中:
def test(request):
print(type(request))
return HttpResponse("test ok!
")
请求来的request是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