Pagination
This commit is contained in:
@ -1,7 +1,7 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Tuple
|
||||
from typing import Any
|
||||
|
||||
from django.db.models import Model, Q, QuerySet
|
||||
from django.core.paginator import Page, Paginator
|
||||
from django.db.models import Q, QuerySet
|
||||
|
||||
from project.main.models import Area, County
|
||||
from project.main.views.demo_view_base import DemoViewBase
|
||||
@ -13,34 +13,16 @@ def get_all_counties() -> QuerySet[County]:
|
||||
return County.objects.all()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Pagination:
|
||||
page: int
|
||||
page_size: int
|
||||
page_count: int
|
||||
prev_page: int
|
||||
next_page: int
|
||||
|
||||
|
||||
class FilterListViewBase(DemoViewBase):
|
||||
def paginate(self, qs: QuerySet[Area]) -> Tuple[QuerySet[Area], Pagination]:
|
||||
def paginate(self, qs: QuerySet[Area]) -> Page:
|
||||
page = int(self.request.GET.get("page", 1))
|
||||
page_size = int(self.request.GET.get("page_size", PAGE_SIZE))
|
||||
|
||||
start_offs = (page - 1) * page_size
|
||||
end_offs = start_offs + page_size
|
||||
|
||||
page_count = int(qs.count() / page_size)
|
||||
|
||||
pagination = Pagination(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
page_count=page_count,
|
||||
prev_page=page - 1 if page > 1 else None,
|
||||
next_page=page + 1 if page < page_count else None,
|
||||
paginator = Paginator(
|
||||
object_list=qs,
|
||||
per_page=page_size,
|
||||
)
|
||||
|
||||
return qs[start_offs:end_offs], pagination
|
||||
return paginator.get_page(page)
|
||||
|
||||
|
||||
class FilterListView(FilterListViewBase):
|
||||
@ -51,14 +33,13 @@ class FilterListView(FilterListViewBase):
|
||||
def get_context_data(self, **kwargs) -> dict[str, Any]:
|
||||
context_data = super().get_context_data(**kwargs)
|
||||
|
||||
qs, pagination = self.paginate(
|
||||
page = self.paginate(
|
||||
qs=Area.objects.select_related("county", "post_office").all(),
|
||||
)
|
||||
context_data.update(
|
||||
{
|
||||
"areas": qs,
|
||||
"page": page,
|
||||
"counties": get_all_counties(),
|
||||
"pagination": pagination,
|
||||
}
|
||||
)
|
||||
return context_data
|
||||
@ -82,15 +63,14 @@ class FilterListFilterView(FilterListViewBase):
|
||||
if county:
|
||||
q &= Q(county_id=county)
|
||||
|
||||
qs, pagination = self.paginate(
|
||||
page = self.paginate(
|
||||
qs=Area.objects.select_related("county", "post_office").filter(q),
|
||||
)
|
||||
|
||||
context_data.update(
|
||||
{
|
||||
"areas": qs,
|
||||
"page": page,
|
||||
"counties": get_all_counties(),
|
||||
"pagination": pagination,
|
||||
}
|
||||
)
|
||||
return context_data
|
||||
|
||||
Reference in New Issue
Block a user