Django教程:什么是get_queryset?为什么不需要“model=poll”?

2024-06-11 05:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在Django官方教程中,引入了“通用视图”。在

我们有:

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

        def get_queryset(self):
            """Return the last five published polls."""
            return Poll.objects.order_by('-pub_date')[:5]


    class DetailView(generic.DetailView):
        model = Poll
        template_name = 'polls/detail.html'
(...)

(网址:https://docs.djangoproject.com/en/1.6/intro/tutorial04/#amend-views

上面写着:

Each generic view needs to know what model it will be acting upon. This is provided using the model attribute.

1/那么为什么我们在IndexView类中没有model = poll,就像在DetailView类中一样?在

2/第二个问题,也许也是相关的问题是:什么是def get_queryset(),我们为什么需要它?我们不能做一些类似queryset = Poll.objects.order_by('-pub_date')[:5](就像类属性一样)吗?在


Tags: thenamegetmodeldefhtmltemplategeneric
2条回答
  1. 因为我们在重写get_queryset时不需要它,因为我们直接在那里指定查询。

  2. 不,因为[:5]会导致查询集立即被计算。如果我们把它放在模型定义中,那么对视图的所有请求都将使用相同的5项:即使添加了新的轮询,它们也永远不会出现在已评估的列表中(直到服务器重新启动或进程终止)。

这是一个完整的答案,基于文件阅读,测试,答案在这里(感谢丹尼尔罗斯曼和knbk,半猜测(所以请告诉我,如果我错了)。在

一般视图确实需要知道在哪个模型上执行。这是因为通用视图必须在后台执行一个查询来检索所需的对象(这将因视图类型而异,ListViewDetailView等)。 所以当调用方法as_view()时,首先调用get_queryset(),并返回{}属性的值。如果没有设置后者,则调用模型对象管理器(poll.objects)的all()方法。在

注:ListViewget_queryset()isn'nt very clear,而{}seems to confirm the above behavior

Returns the queryset that will be used to retrieve the object that this view will display. By default, get_queryset() returns the value of the queryset attribute if it is set, otherwise it constructs a QuerySet by calling the all() method on the model attribute’s default manager.

只是它说all()方法会在我认为^{应该是的时候被调用,因为它是“DetailView”,而不是{}。在

最后,正如knbk所提到的(并在文档中得到确认),在没有step参数的切片时,查询集不会被评估,这意味着在问题的示例中(=在Django官方教程中),将queryset = Poll.objects.order_by('-pub_date')[:5]放在一起也能很好地工作(django1.6测试)。在

相关问题 更多 >