【发布时间】:2019-03-23 20:11:15
【问题描述】:
我仍然习惯于基于类的视图,虽然我了解了一般用途,但有些事情仍然无法理解。我正在关注一个教程,该教程基本上会引导您完成动作,但往往会忽略模糊的细节,例如这段代码:
class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
"""Generic class-based view listing books on loan to current user."""
model = BookInstance
template_name ='books/bookinstance_list_borrowed_user.html'
paginate_by = 1
def get_queryset(self):
return BookInstance.objects.filter(
borrower=self.request.user
).filter(status__exact='o').order_by('due_back')
我得到了model、template_name 和paginate_by 部分,它们是ListView 类的属性,但是我没有得到get_queryset 部分,它在哪里执行?如下面的代码所示,它被称为无处。它返回到哪里?我想我的第一个问题可以归结为“基于类的视图中的函数有什么作用?”
{% extends "base_generic.html" %}
{% block content %}
<h1>Borrowed books</h1>
{% if bookinstance_list %}
<ul>
{% for bookinst in bookinstance_list %}
<li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
<a href="{% url 'book-detail' bookinst.book.pk %}">{{bookinst.book.title}}</a> ({{ bookinst.due_back }})
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no books borrowed.</p>
{% endif %}
那么,有两个问题,第一,get_queryset 返回到哪里,第二,什么是 bookinstance_list?它不是上下文变量,但似乎是突然使用的,为什么这个变量可以使用?
【问题讨论】:
标签: python django python-3.x django-views