Python 将基于函数的视图转换为基于类的视图
我认为应该更简单,但这里是我的基于函数的过滤器视图Python 将基于函数的视图转换为基于类的视图,python,django,Python,Django,我认为应该更简单,但这里是我的基于函数的过滤器视图 def withSub(request): post = Post.objects.filter(with_or_without_sub='WS') paginator = Paginator(post, 2) page = request.GET.get('page') post = paginator.get_page(page) content_dict = { 'posts':
def withSub(request):
post = Post.objects.filter(with_or_without_sub='WS')
paginator = Paginator(post, 2)
page = request.GET.get('page')
post = paginator.get_page(page)
content_dict = {
'posts':post,
'paginator':paginator
}
return render(request, 'community/withSub.html', content_dict)
我只想以如下格式将其切换到基于类的视图,我只想像在函数视图中一样将过滤器放到Post模型中
class PostListView(ListView):
model = Post
template_name = 'community/home.html' # <app>/<model>_<viewtype>.html
类PostListView(ListView):
型号=员额
模板_name='community/home.html'#/_.html
可能是如下所示。您可能需要进行测试和调试。使用了请求.GET
,因此它是GET
from django.views.generic.list import ListView
class PostListView(ListView):
model = Post
template_name = 'community/home.html' # <app>/<model>_<viewtype>.html
def get(self, request, *args, **kwargs):
post = Post.objects.filter(with_or_without_sub='WS')
paginator = Paginator(post, 2)
page = request.GET.get('page')
post = paginator.get_page(page)
content_dict = {
'posts':post,
'paginator':paginator
}
context = self.get_context_data()
context.update(content_dict)
return self.render_to_response(context)
从django.views.generic.list导入ListView
类PostListView(ListView):
型号=员额
模板_name='community/home.html'#/_.html
def get(自我、请求、*args、**kwargs):
post=post.objects.filter(带\u或不带\u sub='WS')
paginator=paginator(职位,2)
page=request.GET.GET('page')
post=分页器。获取页面(第页)
内容目录={
"岗位":岗位,,
“分页器”:分页器
}
context=self.get\u context\u data()
上下文更新(内容)
返回self.render\u to\u响应(上下文)
如果要自定义查询集,请使用queryset
属性:
class PostListView(ListView):
queryset = Post.objects.filter(with_or_without_sub='WS')
template_name = 'community/home.html'
您可以设置一个特定的查询集,如下所示:
queryset = Post.objects.filter(with_or_without_sub='WS')
from django.views.generic.list import ListView
class PostListView(ListView):
model = Post
template_name = 'community/home.html'
def get_queryset(self):
return Post.objects.filter(with_or_without_sub='WS', ...)
或者,如果最终涉及到更复杂的逻辑,您可以覆盖视图的get\u queryset()
方法,如下所示:
queryset = Post.objects.filter(with_or_without_sub='WS')
from django.views.generic.list import ListView
class PostListView(ListView):
model = Post
template_name = 'community/home.html'
def get_queryset(self):
return Post.objects.filter(with_or_without_sub='WS', ...)
你有什么问题?这两种观点根本不一样。为什么要在get_context_data方法中做这些额外的事情?为什么不使用函数一中的逻辑呢?@KostasLivieratos db not found我从frustration@DanielRoseman我只是想将基于类的视图中的model=post更改为post=post.objects.filter(带或不带\u sub='WS'),那么,您为什么不这样做呢?为什么要把投票搞得乱七八糟?