mel*_*lis 7 django django-views
在数据库中,我有一组问题.我想将可折叠项目中的每个问题显示为列表.以前我用的是TemplateView:
class questionmanager(TemplateView):
template_name = 'questionmanager.html'
questions = Question.objects.all()
def get_context_data(self, **kwargs):
context = ({
'questions': self.questions,
})
return context
Run Code Online (Sandbox Code Playgroud)
然后,我读到使用ListView是更好的做法来表示对象列表.然后我改变了我的课程:
class QuestionListView(ListView):
model = Question
def get_context_data(self, **kwargs):
context = super(QuestionListView, self).get_context_data(**kwargs)
return context
Run Code Online (Sandbox Code Playgroud)
在旧模板中,我使用了这个循环:
{% for question in questions %}
Run Code Online (Sandbox Code Playgroud)
当我使用ListView而不是TemplateView时,我以为我不需要使用for循环; 但我无法列出没有for循环的项目.我在这里找到了一个例子,在我看来,唯一的区别是在for循环中我们使用object_list({% for question in **object_list** %})而不是使用我们在上下文中传递的参数.
我真的没有看到使用TemplateView和ListView之间的这么多差异 - 花了一个小时就可以了.如果有人解释为什么使用ListView而不是TemplateView是一种更好的做法(在这种情况下),我将不胜感激.
提前致谢.
对于像这样的简单用例,没有太大区别.但是,ListView在这个例子中更清洁,因为它可以简化为:
class QuestionListView(ListView):
model = Question
Run Code Online (Sandbox Code Playgroud)
考虑到你没有把任何东西放在上下文中.TemplateView's作为一个基本视图是相当基础的,并提供了一组更小的方法和属性来处理更复杂的用例,这意味着你必须在这样的实例中编写更多的代码.如果您在这里查看并比较TemplateView和ListView两个视图,您可以更清楚地看到差异.分页是一个很好的例子,为ListView您分页,只需设置paginate_by属性并相应地修改模板即可.
另请注意,您可以object_list通过context_object_name在"ListView"中进行设置来更改默认名称
| 归档时间: |
|
| 查看次数: |
2588 次 |
| 最近记录: |