gpt4 book ai didi

django - 在 Django 中使用 TemplateView 和 ListView 有什么区别?

转载 作者:行者123 更新时间:2023-12-04 12:07:42 25 4
gpt4 key购买 nike

在数据库中,我有一组问题。我想将可折叠项目中的每个问题显示为列表。以前我用过TemplateView:

class questionmanager(TemplateView):
template_name = 'questionmanager.html'
questions = Question.objects.all()

def get_context_data(self, **kwargs):
context = ({
'questions': self.questions,
})
return context

然后,我读到使用 ListView 是表示对象列表的更好做法。然后我把我的类(class)改成了这样:
class QuestionListView(ListView):
model = Question

def get_context_data(self, **kwargs):
context = super(QuestionListView, self).get_context_data(**kwargs)
return context

在旧模板中,我使用了这个 for 循环:
{% for question in questions %}

当我使用 ListView 而不是 TemplateView 时,我认为我不需要使用 for 循环;但我无法在没有 for 循环的情况下列出项目。我找到了一个例子 here ,在我看来,唯一的区别是在 for 循环中我们使用 object_list ( {% for question in **object_list** %} ) 而不是使用我们在上下文中传递的参数。

在花了一个小时的时间之后,我真的没有看到使用 TemplateView 和 ListView 之间的太大区别。如果有人解释为什么使用 ListView 而不是 TemplateView 是更好的做法(在这种情况下),我将不胜感激。

提前致谢。

最佳答案

对于像这样的简单用例,没有太大区别。然而,ListView在这个例子中更简洁,因为它可以简化为:

class QuestionListView(ListView):
model = Question

考虑到您没有在上下文中放置任何内容。 TemplateView's作为基本 View ,它提供了一组小得多的方法和属性以用于更复杂的用例,这意味着您必须在此类实例中编写更多代码。如果您查看并比较两个 View TemplateViewListView在这里,您可以更清楚地看到差异。分页是一个很好的例子,对 ListView 进行分页您只需设置 paginate_by属性并相应地修改您的模板。

另请注意,您可以更改默认名称 object_list通过设置 context_object_name在“ ListView ”中

关于django - 在 Django 中使用 TemplateView 和 ListView 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25335154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com