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:

View File

@@ -88,8 +88,22 @@
/>
</th>
{% endif %}
{% for label in fields_label %}
<th>{{ label }}</th>
{% for field in fields %}
<th {% for k,v in column_attributes[loop.index0].items() %}{{ k }}="{{ v }}"{% endfor %}>
{% set current_order = request.query_params.get('order_by', '') %}
{% set is_desc = current_order.startswith('-') %}
{% if current_order.lstrip('-') == field.name %}
{% set order_by = '-' + field.name if not is_desc else field.name %}
{% else %}
{% set order_by = field.name %}
{% endif %}
<a href="{{ request.url.include_query_params(order_by=order_by) }}">
{{ field.label }}
{% if current_order.lstrip('-') == field.name %}
{% if is_desc %}&#x25BC;{% else %}&#x25B2;{% endif %}
{% endif %}
</a>
</th>
{% endfor %}
{% if model_resource.actions %}
<th></th>