feat: Add optional ordering feature for resources

Implemented optional ordering of resources in FastAPI admin. Code has been added to accept an 'order_by' parameter in the resource route, if present the list of resources will be sorted accordingly. Templates were updated to support this feature by adding a clickable link to each column header for sorting.
This commit is contained in:
cvelazquez
2024-02-28 08:45:53 -03:00
parent 776083144e
commit fa4fa47fd5
2 changed files with 21 additions and 2 deletions

View File

@ -1,3 +1,5 @@
from typing import Optional
from fastapi import APIRouter, Depends, Path
from jinja2 import TemplateNotFound
from starlette.requests import Request
@ -25,6 +27,7 @@ async def list_view(
resource: str = Path(...),
page_size: int = 10,
page_num: int = 1,
order_by: Optional[str] = None,
):
fields_label = model_resource.get_fields_label()
fields = model_resource.get_fields()
@ -33,6 +36,8 @@ async def list_view(
params, qs = await model_resource.resolve_query_params(request, dict(request.query_params), qs)
filters = await model_resource.get_filters(request, params)
total = await qs.count()
if order_by:
qs = qs.order_by(order_by)
if page_size:
qs = qs.limit(page_size)
else: