何时在Django中使用get,get_queryset,get_context_data? [英] When to use get, get_queryset, get_context_data in Django?

查看:922
本文介绍了何时在Django中使用get,get_queryset,get_context_data?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近得知,当你特别想要做一些不同于默认视图的事情时,你应该重写get方法:

  class ExampleView(generic.ListView):
template_name ='ppm / ppm.html'

def get(self,request):
manager = request.GET.get ('manager',None)
如果manager:
profiles_set = EmployeeProfile.objects.filter(manager = manager)
else:
profiles_set = EmployeeProfile.objects.all()
context = {
'profiles_set':profiles_set,
'title':'Employee Profiles'
}

很简单,但是什么时候应该使用get_queryset或get_context_data?对我来说,似乎他们基本上做同样的事情,还是我只是想念一些东西?我可以一起使用吗?



所以重申:在什么情况下,我可以使用get_queryset或get_context_data,反之亦然?

解决方案

他们确实做了不同的事情。



get() / code>



这是一个顶级方法,每个HTTP动词都有一个 - get() post() patch()等等当你想做某事时你会重写它在请求被视图处理之前或之后。但是,仅当首次加载表单视图时,才会调用此表单,而不是在提交表单时调用。 文档中的基本示例。默认情况下,它将渲染配置的模板并返回HTML。

 类MyView(TemplateView):
#。其他方法

def get(self,* args,** kwargs):
print('处理GET请求')
resp = super()。get(* args,** kwargs)
print('完成处理GET请求')
返回resp



get_query_set()



ListView s - 它确定要显示的对象的列表。默认情况下,它将为您指定的型号提供所有的功能。通过覆盖此方法,您可以扩展或完全替换此逻辑。 有关此主题的Django文档

  class FilteredAuthorView(ListView):
template_name ='authors.html'
model = b
$ b def get_queryset(self):
#original qs
qs = super()。get_queryset()
#通过从url捕获的变量过滤,例如
return qs.filter(name__startswith = self.kwargs.name)



get_context_data()



此方法用于填充字典以用作模板上下文。例如, ListView 将会将 get_queryset()的结果填充为 author_list 在上面的例子。您可能会最为频繁地覆盖此方法来添加要显示在模板中的内容。

  def get_context_data(self,** kwargs )
data = super()。get_context_data(** kwargs)
data ['page_title'] ='作者'
返回数据
/ pre>

然后在您的模板中,您可以引用这些变量。

 < h1> {{page_title}}< / h1> 

< ul>
{author_list%}中的作者的$%
< li> {{author.name}}< / li>
{%endfor%}
< / ul>






现在回答你的主要问题,有这么多的方法是让您轻松地按照定位精度粘贴您的定制逻辑。它不仅允许您的代码更加可读和模块化,而且还可以测试。



文档应该解释一切。如果还不够,您可能会发现来源也有帮助。你会看到一切都是用mixin实现的,只有这样才能实现,因为一切都是划分的。


I recently learned that you should override the get method when you specifically want to do something other than what the default view does:

class ExampleView(generic.ListView):
    template_name = 'ppm/ppm.html'

    def get(self, request):
        manager = request.GET.get('manager', None)
        if manager:
            profiles_set = EmployeeProfile.objects.filter(manager=manager)
        else:
            profiles_set = EmployeeProfile.objects.all()
            context = {
                'profiles_set': profiles_set,
                'title': 'Employee Profiles'
            }

That's simple enough, but when should I use get_queryset or get_context_data over get? To me it seems like they basically do the same thing or am I just missing something? Can I use them together? This is a major source of confusion for me.

So to reiterate: In what cases would I use get over get_queryset or get_context_data and vise versa?

解决方案

They indeed do different things.

get()

This is a top-level method, and there's one for each HTTP verb - get(), post(), patch(), etc. You would override it when you want to do something before a request is processed by the view, or after. But this is only called when a form view is loaded for the first time, not when the form is submitted. Basic example in the documentation. By default it will just render the configured template and return the HTML.

class MyView(TemplateView):
    # ... other methods

    def get(self, *args, **kwargs):
        print('Processing GET request')
        resp = super().get(*args, **kwargs)
        print('Finished processing GET request')
        return resp

get_query_set()

Used by ListViews - it determines the list of objects that you want to display. 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.

class FilteredAuthorView(ListView):
    template_name = 'authors.html'
    model = Author

    def get_queryset(self):
        # original qs
        qs = super().get_queryset() 
        # filter by a variable captured from url, for example
        return qs.filter(name__startswith=self.kwargs.name)

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 author_list in the above example. 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['page_title'] = 'Authors'
    return data

And then in your template you can reference these variables.

<h1>{{ page_title }}</h1>

<ul>
{% for author in author_list %}
    <li>{{ author.name }}</li>
{% endfor %}
</ul>


Now to answer your main question, the reason you have so many methods is to let you easily stick your custom logic with pin-point accuracy. It not only allows your code to be more readable and modular, but also more testable.

The documentation should explain everything. If still not enough, you may find the sources helpful as well. You'll see how everything is implemented with mixins which are only possible because everything is compartmentalized.

这篇关于何时在Django中使用get,get_queryset,get_context_data?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆