From 044f76a059cc414f5ac5f8132ff4950fabf1e105 Mon Sep 17 00:00:00 2001 From: Ole Magnus Fon Johnsen Date: Tue, 29 Jul 2025 16:01:18 +0200 Subject: [PATCH] Fix order by sample name --- src/genlab_bestilling/managers.py | 2 +- src/staff/tables.py | 24 ++++++------------------ 2 files changed, 7 insertions(+), 19 deletions(-) diff --git a/src/genlab_bestilling/managers.py b/src/genlab_bestilling/managers.py index 18bbd5e0..b912cb6b 100644 --- a/src/genlab_bestilling/managers.py +++ b/src/genlab_bestilling/managers.py @@ -85,7 +85,7 @@ def annotate_numeric_name(self) -> QuerySet: return self.annotate( name_as_int=Case( When( - name__regex=r"^\d{,18}$", + name__regex=r"^\d{1,18}$", then=Cast("name", BigIntegerField()), ), default=Value(None), diff --git a/src/staff/tables.py b/src/staff/tables.py index f0c1460d..133a4dba 100644 --- a/src/staff/tables.py +++ b/src/staff/tables.py @@ -1,8 +1,7 @@ -import re -from collections.abc import Sequence from typing import Any import django_tables2 as tables +from django.db.models import QuerySet from django.templatetags.static import static from django.utils.html import format_html from django.utils.safestring import mark_safe @@ -312,22 +311,11 @@ def render_checked(self, record: Any) -> str: ) def order_name( - self, records: Sequence[Any], is_descending: bool - ) -> tuple[list[Any], bool]: - def natural_sort_key(record: Any) -> list[str]: - name = record.name or "" - parts = re.findall(r"\d+|\D+", name) - key = [] - for part in parts: - if part.isdigit(): - # Pad numbers with zeros for proper string compare, e.g., '000012' > '000001' # noqa: E501 - key.append(f"{int(part):010d}") - else: - key.append(part.lower()) - return key - - sorted_records = sorted(records, key=natural_sort_key, reverse=is_descending) - return (sorted_records, True) + self, queryset: QuerySet[Sample], is_descending: bool + ) -> tuple[QuerySet[Sample], bool]: + prefix = "-" if is_descending else "" + queryset = queryset.order_by(f"{prefix}name_as_int", "name") + return (queryset, True) class SampleStatusTable(tables.Table):