2016-04-28 84 views
1

我一直在学习Django,我有一个混淆的来源是基于类的视图以及何时重写get方法。我查看了文档,它解释了什么,但它不能解释什么时候应该重写get。何时重写Django CBV中的get方法?

我最初创建一个视图是这样的:

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

    def get(self, request): 
     profiles_set = EmployeeProfile.objects.all() 
     context = { 
      'profiles_set': profiles_set, 
      'title': 'Employee Profiles' 
     } 
     return render(request, self.template_name, context) 

但我最近告诉我的代码很简单的足够的默认实现,所有我需要的是这样的:

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

所以我的问题是这样的:在什么情况/情况下我应该重写get方法?

回答

3

如果您使用的是内置的通用视图,那么你应该很少有覆盖get()。你最终会复制很多功能,或者中断视图的功能。

例如,paginate_by选项将不再适用于您的视图,因为您没有在get()方法中对查询集进行切片。

如果您使用的是像ListView这样的通用基于类的视图,则应尝试在可能的情况下覆盖特定的属性或方法,而不是覆盖get()

您认为优先于get()的优势在于它非常清楚它的功能。您可以看到该视图提取了一个查询集,将其包含在上下文中,然后呈现模板。你不需要知道ListView就能理解视图。

如果您喜欢替代覆盖get()子类View的明确性。您没有使用ListView的任何功能,因此将其继承是没有意义的。

from django.views.generic import View 

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

    def get(self, request): 
     ... 
0

当您特别想要执行默认视图以外的操作时,您应该重写get方法。在这种情况下,除了使用所有EmployeeProfile对象的列表呈现模板之外,您的代码不会执行任何操作,这正是通用的ListView会执行的操作。

如果你想做更复杂的事情,你可以重写它。比如,也许你想基于URL参数过滤:

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) 
+3

注意这个例子还是不需要你覆盖'得到()' - 这将是更好的覆盖['get_queryset()'](https://docs.djangoproject.com/en/ 1.9/ref/class-based-views/mixins-multiple-object /#django.views.generic.list.MultipleObjectMixin.get_queryset)。 – Alasdair