我有这个ListView,我正尝试从数据库中获取12辆汽车,并按价格对其进行排序,我在数据库中有20个条目,在分页按钮中它显示6个按钮,也就是6页,因此正在从db返回所有可能的数据,这时我迷路了,找不到错误,对于分页和排序都将非常感谢。
class CardListView(ListView):
model = Car
template_name = 'home.html'
context_object_name = 'cars'
ordering = ['-price']
paginate_by = 5
limit = 12
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
paginator = context['paginator']
page_numbers_range = 10
max_index = len(paginator.page_range)
page = self.request.GET.get('page')
current_page = int(page) if page else 1
start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range
end_index = start_index + page_numbers_range
if end_index >= max_index:
end_index = max_index
page_range = paginator.page_range[start_index:end_index]
cars = Car.objects.all()[:self.limit]
car_types = CarCategory.objects.all()
context['cars'] = cars
context['car_types'] = car_types
context['page_range'] = page_range
return context
答案 0 :(得分:2)
您无需自己执行分页逻辑,只需在get_context_data
中实现要传递给模板的 additional 元素即可。分页逻辑由ListView
itself处理。如果要限制查询集,则应在get_queryset(..)
[Django-doc]函数中做到这一点:
class CardListView(ListView):
model = Car
template_name = 'home.html'
context_object_name = 'cars'
ordering = ['-price']
paginate_by = 5
limit = 12
def get_queryset(self):
return super().get_queryset()[:self.limit]
def get_context_data(self, **kwargs):
context = super().get_context_data() # with paginated queryset
context['car_types'] = car_types = CarCategory.objects.all()
return context
原始的ListView
实现将调用get_queryset
,然后将其传递给适当的分页器。通过使用super()
,我们还不需要关心ordering
等。这些都由ListView
本身处理。