When to override get method in Django CBV?

前端 未结 2 1637
温柔的废话
温柔的废话 2021-01-27 12:23

I\'ve been learning Django and one source of confusion I have is with class based views and when to override the get method. I\'ve looked through the documentation and it explai

2条回答
  •  无人共我
    2021-01-27 13:10

    You should override the get method when you specifically want to do something other than the default view does. In this case, your code isn't doing anything other than rendering the template with the list of all EmployeeProfile objects, which is exactly what the generic ListView would do.

    You might override it if you want to do something more complicated. For example, maybe you want to filter based on a URL parameter:

    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'
            }
            return render(request, self.template_name, context)
    

提交回复
热议问题