如何在同一页面中对多个查询集进行分页和排序?
how to paginate and sort multiple querysets in same page?
我在一个页面中使用了两个查询集,我想为每个查询集设置不同的分页
这是我基于 class 的观点:
class MainListView(ListView):
queryset = Post.objects.all()
template_name = 'main.html'
context_object_name = 'posts'
def get_context_data(self, **kwargs):
context = super(MainListView, self).get_context_data(**kwargs)
context['news'] = EventsPost.objects.all()
context['posts'] = self.queryset
return context
我希望 Post 模型按 3 分页,事件 Post 按 6 分页
感谢您的回复
因为不需要分页,我会使用 TemplateView
,并在 get_context_data
方法中将两个查询集添加到上下文中。
class MainListView(TemplateView):
def get_context_data(self, **kwargs):
context = super(MainListView, self).get_context_data(**kwargs)
context['news'] = EventsPost.objects.order_by('-pk')[:6]
context['posts'] = Post.objects.order_by('-pk')[:3]
return context
如果您想在不同的字段上排序,您可以将其更改为其他内容,例如order_by('-date')
我在一个页面中使用了两个查询集,我想为每个查询集设置不同的分页
这是我基于 class 的观点:
class MainListView(ListView):
queryset = Post.objects.all()
template_name = 'main.html'
context_object_name = 'posts'
def get_context_data(self, **kwargs):
context = super(MainListView, self).get_context_data(**kwargs)
context['news'] = EventsPost.objects.all()
context['posts'] = self.queryset
return context
我希望 Post 模型按 3 分页,事件 Post 按 6 分页 感谢您的回复
因为不需要分页,我会使用 TemplateView
,并在 get_context_data
方法中将两个查询集添加到上下文中。
class MainListView(TemplateView):
def get_context_data(self, **kwargs):
context = super(MainListView, self).get_context_data(**kwargs)
context['news'] = EventsPost.objects.order_by('-pk')[:6]
context['posts'] = Post.objects.order_by('-pk')[:3]
return context
如果您想在不同的字段上排序,您可以将其更改为其他内容,例如order_by('-date')