From bd1663ee96c409c06cba6fcf4c74f2a429d8fa2c Mon Sep 17 00:00:00 2001 From: Ole Magnus Fon Johnsen Date: Tue, 15 Jul 2025 19:28:30 +0200 Subject: [PATCH] Proposal --- src/staff/tables.py | 12 +----------- src/staff/views.py | 8 ++++++++ 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/staff/tables.py b/src/staff/tables.py index ee4d8523..aa3d1b54 100644 --- a/src/staff/tables.py +++ b/src/staff/tables.py @@ -2,8 +2,6 @@ from typing import Any import django_tables2 as tables -from django.db.models import IntegerField -from django.db.models.functions import Cast from django.utils.safestring import mark_safe from genlab_bestilling.models import ( @@ -167,7 +165,7 @@ class SampleBaseTable(tables.Table): empty_values=(), ) - name = tables.Column(order_by=("name_as_int",)) + name = tables.Column(order_by=("name_as_int", "name")) class Meta: model = Sample @@ -202,14 +200,6 @@ class Meta: empty_text = "No Samples" - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - if hasattr(self.data, "data"): - self.data.data = self.data.data.annotate( - name_as_int=Cast("name", output_field=IntegerField()) - ) - def render_plate_positions(self, value: Any) -> str: if value: return ", ".join([str(v) for v in value.all()]) diff --git a/src/staff/views.py b/src/staff/views.py index 018584fd..4e0b5322 100644 --- a/src/staff/views.py +++ b/src/staff/views.py @@ -5,6 +5,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.db import models from django.db.models import Count, Exists, OuterRef +from django.db.models.expressions import RawSQL from django.forms import Form from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404 @@ -241,6 +242,13 @@ def get_queryset(self) -> models.QuerySet[Sample]: .prefetch_related("plate_positions") .filter(order=self.kwargs["pk"]) .order_by("species__name", "year", "location__name", "name") + .annotate( + name_as_int=RawSQL( + r"substring(%s from '^\d+$')::int", + params=["name"], + output_field=models.IntegerField(), + ) + ) ) def get_context_data(self, **kwargs) -> dict[str, Any]: