diff --git a/rating_api/models/db.py b/rating_api/models/db.py index 371a6b9..747a983 100644 --- a/rating_api/models/db.py +++ b/rating_api/models/db.py @@ -7,7 +7,7 @@ from sqlalchemy import UUID, DateTime from sqlalchemy import Enum as DbEnum -from sqlalchemy import ForeignKey, Integer, String, and_, or_, true +from sqlalchemy import ForeignKey, Integer, String, and_, func, or_, true from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy.orm import Mapped, mapped_column, relationship @@ -36,7 +36,7 @@ class Lecturer(BaseDbModel): comments: Mapped[list[Comment]] = relationship("Comment", back_populates="lecturer") @hybrid_method - def search(self, query: str) -> bool: + def search_by_name(self, query: str) -> bool: response = true query = query.split(' ') for q in query: @@ -45,6 +45,14 @@ def search(self, query: str) -> bool: ) return response + @hybrid_method + def search_by_subject(self, query: str) -> bool: + query = query.lower() + response = true + if query: + response = and_(Comment.review_status == ReviewStatus.APPROVED, func.lower(Comment.subject).contains(query)) + return response + class Comment(BaseDbModel): uuid: Mapped[uuid.UUID] = mapped_column(UUID, primary_key=True, default=uuid.uuid4) diff --git a/rating_api/routes/lecturer.py b/rating_api/routes/lecturer.py index a5e7f79..99c0cab 100644 --- a/rating_api/routes/lecturer.py +++ b/rating_api/routes/lecturer.py @@ -101,7 +101,11 @@ async def get_lecturers( `name` Поле для ФИО. Если передано `name` - возвращает всех преподователей, для которых нашлись совпадения с переданной строкой """ - lecturers = Lecturer.query(session=db.session).filter(Lecturer.search(name)).all() + lecturers_query = Lecturer.query(session=db.session) + if subject: + lecturers_query = lecturers_query.join(Lecturer.comments).filter(Lecturer.search_by_subject(subject)) + lecturers_query = lecturers_query.filter(Lecturer.search_by_name(name)) + lecturers = lecturers_query.all() if not lecturers: raise ObjectNotFound(Lecturer, 'all') result = LecturerGetAll(limit=limit, offset=offset, total=len(lecturers)) @@ -137,11 +141,6 @@ async def get_lecturers( result.lecturers.append(lecturer_to_result) if "general" in order_by: result.lecturers.sort(key=lambda item: (item.mark_general is None, item.mark_general)) - if subject: - result.lecturers = [ - lecturer for lecturer in result.lecturers if lecturer.subjects and subject in lecturer.subjects - ] - result.total = len(result.lecturers) return result