django - 使用 get_queryset() 方法或设置查询集变量?

标签 django django-views django-generic-views

这两段代码乍一看是相同的:

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'
    queryset = Poll.active.order_by('-pub_date')[:5]

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        return Poll.active.order_by('-pub_date')[:5]

它们之间有什么区别吗?如果是:

哪种方法更好?或者设置 queryset 变量比覆盖 get_queryset 方法更好?反之亦然。

最佳答案

在您的示例中,覆盖 querysetget_queryset 具有相同的效果。我稍微倾向于设置 queryset,因为它不那么冗长。

当您设置queryset 时,查询集只会在您启动服务器时创建一次。另一方面,每个请求都会调用 get_queryset 方法。

这意味着如果您想动态调整查询,get_queryset 很有用。例如,您可以返回属于当前用户的对象:

class IndexView(generic.ListView):
    def get_queryset(self):
        """Returns Polls that belong to the current user"""
        return Poll.active.filter(user=self.request.user).order_by('-pub_date')[:5]

另一个 get_queryset 有用的例子是当你想根据可调用的对象进行过滤时,例如,返回今天的民意调查:

class IndexView(generic.ListView):
    def get_queryset(self):
        """Returns Polls that were created today"""
        return Poll.active.filter(pub_date=date.today())

如果您尝试通过设置 queryset 来做同样的事情,那么 date.today() 只会在加载 View 时调用一次,并且 View 一段时间后会显示不正确的结果。

class IndexView(generic.ListView):
    # don't do this!
    queryset = Poll.active.filter(pub_date=date.today())

关于django - 使用 get_queryset() 方法或设置查询集变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19707237/

相关文章:

python - 更改元组列表,使第一个条目与第二个条目相同

Django-filter:按模型属性过滤

django - 如何配置 Apache 别名设置让 django 调试工具栏正常工作?

python - Django 表单搜索

python - 简而言之,什么是 Django 通用 View ?

django - 在 Django 的 ListView 中排序

python - 向 rabbitmq 发送 celery 任务消息

django - Django 中的应用程序设计

python - Beautiful Soup 迭代 html 标签

django - 我如何从通用更新 View 中获取我的对象ID以在django 1.1中的表单中使用