简体   繁体   English

Django-上下文变量在哪里?

[英]Django - Where is the context variable?

I'm still getting used to class based views, while I get the general purpose, some things still get past me. 我仍然习惯于对基于视图的类进行分类,虽然我已经达到了通用的目的,但是有些事情仍然无法解决。 I'm following a tutorial which basically walks you through the motions but tends to ignore the fuzzy details, such as this piece of code: 我正在遵循一个教程,该教程基本上会带您完成动作,但往往会忽略模糊的细节,例如这段代码:

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')

I get the model, template_name and paginate_by parts, they're attributes of the ListView class, but what I don't get is the get_queryset part, where is it executed? 我得到了模型,template_name和paginate_by部分,它们是ListView类的属性,但是我没有得到的是get_queryset部分,它在哪里执行? As seen in the code below it's called nowhere. 如下面的代码所示,它被称为nowhere。 Where is it returned to? 它又回到了哪里? I guess my first question can be chalked down to "What do functions in class based views do?" 我想我的第一个问题可以归结为“基于类的视图中的函数做什么?”

{% 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 %}       

So, two issues, first, where did the get_queryset return to, and second, what is bookinstance_list? 因此,有两个问题,第一,get_queryset返回到哪里,第二,bookinstance_list是什么? It's not a context variable, but seems to be used out of the blue, why is this variable usable? 它不是一个上下文变量,但是似乎是突然使用的,为什么这个变量可用?

Class Based Views calls get_queryset() in the get() method of your view, I'll present some example code from Django 1.11. 基于类的视图在视图的get()方法中调用get_queryset() ,我将介绍Django 1.11中的一些示例代码。

# django/views/generic/list.py:159
def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()

    ...

    context = self.get_context_data()
    return self.render_to_response(context)

The ListView class sets self.object_list = self.get_queryset() in this method, however this doesn't explain where it sets it in the context passed to your template. ListView类在此方法中设置self.object_list = self.get_queryset() ,但是,这并没有说明它在传递给模板的上下文中将其设置在何处。 If we take a quick look at get_context_data() : 如果快速看一下get_context_data()

# django/views/generic/list.py:127
def get_context_data(self, **kwargs):
    """
    Get the context for this view.
    """
    queryset = kwargs.pop('object_list', self.object_list)
    page_size = self.get_paginate_by(queryset)
    context_object_name = self.get_context_object_name(queryset)
    if page_size:
        paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
        context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'object_list': queryset
        }
    else:
        context = {
            'paginator': None,
            'page_obj': None,
            'is_paginated': False,
            'object_list': queryset
        }
    if context_object_name is not None:
        context[context_object_name] = queryset
    context.update(kwargs)
    return super(MultipleObjectMixin, self).get_context_data(**context)

context is assigned a dictionary with 'object_list': queryset , so when you're trying to access the resulting QuerySet from get_queryset in your template you should access object_list . context被分配了一个带有'object_list': queryset的字典,因此,当您尝试从模板中的get_queryset访问结果QuerySet ,应该访问object_list

The Django documentation on class-based generic views has a section on extending your context data with additional info. 有关基于类的通用视图的Django文档提供了有关使用附加信息扩展上下文数据的部分。 https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/#dynamic-filtering https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/#dynamic-filtering

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM