简体   繁体   English

Django通用视图中get_context_data和queryset之间的差异?

[英]Diference between get_context_data and queryset in Django generic views?

What is the difference between get_context_data and queryset in Django generic views? Django通用视图中get_context_dataqueryset之间有什么区别? They seem to do the same thing? 他们似乎做同样的事情?

get_context_data() get_context_data()

This method is used to populate a dictionary to use as the template context. 此方法用于填充字典以用作模板上下文。 For example, ListViews will populate the result from get_queryset() as object_list. 例如,ListViews将get_queryset()的结果填充为object_list。 You will probably be overriding this method most often to add things to display in your templates. 您可能最常重复使用此方法来添加要在模板中显示的内容。

def get_context_data(self, **kwargs):
    data = super().get_context_data(**kwargs)
    data['some_thing'] = 'some_other_thing'
    return data

And then in your template you can reference these variables. 然后在您的模板中,您可以引用这些变量。

<h1>{{ some_thing }}</h1>

<ul>
{% for item in object_list %}
    <li>{{ item.name }}</li>
{% endfor %}    
</ul>

This method is only used for providing context for the template. 此方法仅用于为模板提供上下文。

get_queryset() get_queryset()

Used by ListViews - it determines the list of objects that you want to display. ListViews - 它确定要显示的对象列表。 By default it will just give you all for the model you specify. 默认情况下,它只会为您指定的模型提供所有内容。 By overriding this method you can extend or completely replace this logic. 通过重写此方法,您可以扩展或完全替换此逻辑。 Django documentation on the subject . 关于这个主题的Django文档

These are completely different things. 这些是完全不同的东西。

get_context_data() is used to generate dict of variables that are accessible in template. get_context_data()用于生成可在模板中访问的变量的dict。 queryset is Django ORM queryset that consists of model instances queryset是由模型实例组成的Django ORM查询集

Default implementation of get_context_data() in ListView adds return value of get_queryset() (which simply returns self.queryset by default) to context as objects_list variable. ListViewget_context_data()默认实现将get_context_data()返回值get_queryset()默认情况下只返回self.queryset )添加到context作为objects_list变量的上下文中。

Why not have a look at the code. 为什么不看看代码。

http://ccbv.co.uk/projects/Django/1.11/django.views.generic.list/ListView/ http://ccbv.co.uk/projects/Django/1.11/django.views.generic.list/ListView/

Clicking on the get() method shows that it calls get_queryset() method to get the queryset - which is usually iterated over in a ListView. 单击get()方法显示它调用get_queryset()方法来获取查询集 - 通常在ListView中迭代。

Further down it calls get context_data() where extra variables can be passed to the template. 进一步向下调用get context_data(),其中可以将额外的变量传递给模板。

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

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