From c12e3a58c30a262d06c5e0dc065a69212dd22b2e Mon Sep 17 00:00:00 2001 From: SKairinos Date: Tue, 24 Sep 2024 10:06:02 +0000 Subject: [PATCH] search classes by their id or name --- codeforlife/user/filters/klass.py | 12 +++++++++++- codeforlife/user/views/klass_test.py | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/codeforlife/user/filters/klass.py b/codeforlife/user/filters/klass.py index 7e832290..58b23eb6 100644 --- a/codeforlife/user/filters/klass.py +++ b/codeforlife/user/filters/klass.py @@ -3,6 +3,8 @@ Created on 24/07/2024 at 13:19:57(+01:00). """ +from django.db.models import Q # isort: skip +from django.db.models.query import QuerySet # isort: skip from django_filters import ( # type: ignore[import-untyped] # isort: skip rest_framework as filters, ) @@ -16,6 +18,14 @@ class ClassFilterSet(FilterSet): _id = filters.CharFilter(method="_id__method") _id__method = FilterSet.make_exclude_field_list_method("access_code") + id_or_name = filters.CharFilter(method="id_or_name__method") + + def id_or_name__method(self, queryset: QuerySet[Class], _: str, value: str): + """Get classes where the id or the contain a substring.""" + return queryset.filter( + Q(access_code__icontains=value) | Q(name__icontains=value) + ) + class Meta: model = Class - fields = ["_id", "teacher"] + fields = ["_id", "teacher", "id_or_name"] diff --git a/codeforlife/user/views/klass_test.py b/codeforlife/user/views/klass_test.py index 8fe707bd..f9275a70 100644 --- a/codeforlife/user/views/klass_test.py +++ b/codeforlife/user/views/klass_test.py @@ -97,6 +97,31 @@ def test_list___id(self): filters={"_id": first_class.access_code}, ) + def test_list__id_or_name(self): + """ + Can successfully list classes in a school, filtered by their ID or name. + """ + user = self.admin_school_teacher_user + assert user + + klass = user.teacher.classes.first() + assert klass + + partial_access_code = klass.access_code[:-1] + partial_name = klass.name[:-1] + + self.client.login_as(user) + self.client.list( + models=user.teacher.classes.filter( + access_code__icontains=partial_access_code + ), + filters={"id_or_name": partial_access_code}, + ) + self.client.list( + models=user.teacher.classes.filter(name__icontains=partial_name), + filters={"id_or_name": partial_name}, + ) + def test_list__teacher(self): """Can successfully list classes assigned to a teacher.""" user = self.admin_school_teacher_user