什么时候在 Django 中使用 get、get_queryset、get_context_data? [英] When to use get, get_queryset, get_context_data in Django?

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

问题描述

我最近了解到,当您特别想要执行默认视图以外的其他操作时,您应该覆盖 get 方法:

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

这很简单,但是我什么时候应该使用 get_querysetget_context_data 而不是 get ?对我来说,他们似乎基本上做同样的事情,还是我只是错过了什么?我可以一起使用它们吗?这对我来说是一个主要的困惑来源.

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.

重申:在什么情况下我会使用 get over get_querysetget_context_data 反之亦然?

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.

这是一个顶级方法,每个 HTTP 动词都有一个 - get(), post(), patch()> 等.当您想在视图处理请求之前或之后执行某些操作时,您可以覆盖它.但这仅在第一次加载表单视图时调用,而不是在提交表单时调用.文档中的基本示例.默认情况下,它只会呈现配置的模板并返回 HTML.

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_queryset()

ListViews 使用 - 它确定要显示的对象列表.默认情况下,它只会为您指定的模型提供所有信息.通过覆盖此方法,您可以扩展或完全替换此逻辑.Django 文档主题.

get_queryset()

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

此方法用于填充字典以用作模板上下文.例如,ListViews 会将 get_queryset() 的结果填充为上述示例中的 author_list.您可能最常覆盖此方法以添加要在模板中显示的内容.

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.

文档应该解释一切.如果仍然不够,您可能会发现来源也很有帮助.您将看到一切都是如何使用 mixin 实现的,因为一切都是分开的.

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天全站免登陆