Python 何时在Django CBV中重写get方法?
我一直在学习Django,我感到困惑的一个原因是基于类的视图以及何时重写get方法。我浏览了文档,它解释了get的作用,但没有解释何时应该重写get 我最初是这样创建视图的:Python 何时在Django CBV中重写get方法?,python,django,django-class-based-views,Python,Django,Django Class Based Views,我一直在学习Django,我感到困惑的一个原因是基于类的视图以及何时重写get方法。我浏览了文档,它解释了get的作用,但没有解释何时应该重写get 我最初是这样创建视图的: class ExampleView(generic.ListView): template_name = 'ppm/ppm.html' paginate_by = 5 def get(self, request): profiles_set = EmployeeProfile.ob
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方法 当您特别想执行默认视图之外的操作时,应该重写
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)
当您特别希望执行默认视图之外的操作时,应该重写
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)
如果您使用的是内置的通用视图,那么您应该很少需要重写
get()
。您将要么复制大量功能,要么破坏视图的功能
例如,该选项将不再在视图中工作,因为您没有在get()
方法中切片queryset
如果您使用的是基于类的通用视图,如ListView
,则应尽可能覆盖特定的属性或方法,而不是覆盖get()
覆盖get()
的视图的优点是它的功能非常明确。您可以看到,该视图获取查询集,将其包含在上下文中,然后呈现模板。您不需要了解ListView
就可以理解该视图
如果您喜欢重写get()
子类的明确性。您没有使用ListView
的任何功能,因此将其子类化是没有意义的
from django.views.generic import View
class ExampleView(View):
template_name = 'ppm/ppm.html'
def get(self, request):
...
如果您使用的是内置的通用视图,那么您应该很少需要重写
get()
。您将要么复制大量功能,要么破坏视图的功能
例如,该选项将不再在视图中工作,因为您没有在get()
方法中切片queryset
如果您使用的是基于类的通用视图,如ListView
,则应尽可能覆盖特定的属性或方法,而不是覆盖get()
覆盖get()
的视图的优点是它的功能非常明确。您可以看到,该视图获取查询集,将其包含在上下文中,然后呈现模板。您不需要了解ListView
就可以理解该视图
如果您喜欢重写get()
子类的明确性。您没有使用ListView
的任何功能,因此将其子类化是没有意义的
from django.views.generic import View
class ExampleView(View):
template_name = 'ppm/ppm.html'
def get(self, request):
...
请注意,此示例仍然不要求您重写
get()
-最好改为重写。请注意,此示例仍然不要求您重写get()
-最好改为重写。