我正在开始一个新的应用程序,我正在尽我所能接受基于类的视图。啊,成长的痛苦。我正在尝试从 GET 变量在这里做一个简单的过滤器,如果它不存在,我想返回按 id desc 排序的所有对象,如果是,我想过滤、排序并返回过滤后的列表。
我正在编写 30 多行代码来执行此操作,所以我一定做错了什么,对吧?我尝试覆盖 get_queryset() ,现在我想到了,也许我应该在 get_queryset() 中调用 self.request.GET['search'] 来执行此过滤。有没有标准的方法来完成这个?
class MyModelList(AdminPageMixin, ListView):
model = MyModel
context_object_name = 'object'
template_name = 'template/list.html'
def get(self, request, *args, **kwargs):
if 'search' in request.GET and len(request.GET['search']):
search = request.GET['search']
self.object_list = MyModel.objects.filter(advertiser__name=search).orderby('-id')
context = self.get_context_data(object_list=self.object_list, search=search)
else:
self.object_list = MyModel.objects.all()
context = self.get_context_data(object_list=self.object_list).orderby('-id')
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(MyModelList, self).get_context_data(**kwargs)
form = MyModelForm
try:
context['search'] = kwargs['search']
except KeyError:
pass
context['form'] = form
context['form_action'] = reverse('mymodel-add')
context['form_display'] = 'hide'
context['form_save_label'] = 'Add'
return context
其次,为了使事情复杂化,我有一个 CreateView 和一个 UpdateView,我想共享我的 ListView 的 get() 或 get_queryset() 和 get_context_data() 方法。我确信使用 Mixin 是可能的,但同样,我正在寻找一种标准化的方式来做这件事。建议?这是我想在其中分享 ListView 方法的 CreateView。
class MyModelAdd(AdminPageMixin, CreateView):
model = MyModel
form_class = MyModelForm
context_object_name = 'object'
template_name = 'templates/list.html'
def get_success_url(self):
return reverse('mymodel-list')
def get_context_data(self, **kwargs):
context = super(MyModelAdd, self).get_context_data(**kwargs)
context['form_action'] = reverse('mymodel-add')
context['form_display'] = 'show'
context['object_list'] = MyModel.objects.all()
return context
def form_invalid(self, form):
form = MyModelForm(self.request.POST)
context = self.get_context_data()
context['form'] = form
context['form_action'] = reverse('mymodel-add')
context['form_display'] = 'show'
context['form_save_label'] = 'Add'
return render(self.request, 'templates/list.html', context)