Skip to content

Commit

Permalink
Merge branch 'main' into front/changes-ui-errors-message
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielCastelo-31 authored Aug 14, 2024
2 parents e368bb1 + 0b36d58 commit 4887e24
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 13 deletions.
24 changes: 11 additions & 13 deletions api/api/views/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from unidecode import unidecode
from ..models import Class, Discipline
from ..models import Discipline

from django.contrib import admin
from django.db.models.query import QuerySet

from rest_framework.decorators import APIView
Expand All @@ -13,6 +11,7 @@
from utils.sessions import get_current_year_and_period, get_next_period
from utils.schedule_generator import ScheduleGenerator
from utils.db_handler import get_best_similarities_by_name, filter_disciplines_by_teacher, filter_disciplines_by_year_and_period, filter_disciplines_by_code
from utils.search import SearchTool

from .. import serializers
from api.swagger import Errors
Expand All @@ -37,17 +36,16 @@ def treat_string(self, string: str | None) -> str | None:
return string

def filter_disciplines(self, request: request.Request, name: str) -> QuerySet[Discipline]:
unicode_name = unidecode(name).casefold()
model_handler = admin.ModelAdmin(Discipline, admin.site)
model_handler.search_fields = [
'unicode_name', 'code']

disciplines = Discipline.objects.all()

disciplines, _ = model_handler.get_search_results(
request, disciplines, unicode_name)
search_handler = SearchTool(Discipline)
search_fields = ['unicode_name', 'code']

result = search_handler.filter_by_search_result(
request = request,
search_str = name,
search_fields = search_fields
)

return disciplines
return result

def retrieve_disciplines_by_similarity(self, request: request.Request, name: str) -> QuerySet[Discipline]:
disciplines = self.filter_disciplines(request, name)
Expand Down
25 changes: 25 additions & 0 deletions api/utils/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.contrib.admin import ModelAdmin, site
from django.db.models.query import QuerySet
from django.db.models import Model
from rest_framework.request import Request
from unidecode import unidecode
from typing import Any, Type

class SearchTool:
"""
Search for models by given model fields and a search string.
"""
def __init__(self, model: Type[Model]) -> None:
self.model = model

def filter_by_search_result(self, request: Request, search_str: str, search_fields: list[str]) -> QuerySet[Any]:
unicode_search_str = unidecode(search_str).casefold()
model_handler = ModelAdmin(self.model, site)
model_handler.search_fields = search_fields

values = self.model.objects.all()

values, _ = model_handler.get_search_results(
request, values, unicode_search_str)

return values

0 comments on commit 4887e24

Please sign in to comment.