Skip to content

Commit

Permalink
search classes by their id or name
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Sep 24, 2024
1 parent 14403ef commit c12e3a5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
12 changes: 11 additions & 1 deletion codeforlife/user/filters/klass.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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"]
25 changes: 25 additions & 0 deletions codeforlife/user/views/klass_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c12e3a5

Please sign in to comment.