Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix sort lecturers #48

Merged
merged 9 commits into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion rating_api/models/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from sqlalchemy import UUID, Boolean, DateTime
from sqlalchemy import Enum as DbEnum
from sqlalchemy import ForeignKey, Integer, String, and_, func, or_, true
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy.ext.hybrid import hybrid_method, hybrid_property
from sqlalchemy.orm import Mapped, mapped_column, relationship

from rating_api.settings import get_settings
Expand Down Expand Up @@ -74,6 +74,10 @@ class Comment(BaseDbModel):
review_status: Mapped[ReviewStatus] = mapped_column(DbEnum(ReviewStatus, native_enum=False), nullable=False)
is_deleted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

@hybrid_property
def mark_general(self):
return (self.mark_kindness + self.mark_freebie + self.mark_clarity) / 3


class LecturerUserComment(BaseDbModel):
id: Mapped[int] = mapped_column(Integer, primary_key=True)
Expand Down
54 changes: 30 additions & 24 deletions rating_api/routes/lecturer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends, Query
from fastapi_sqlalchemy import db
from sqlalchemy import and_
from sqlalchemy import and_, func, nullslast

from rating_api.exceptions import AlreadyExists, ObjectNotFound
from rating_api.models import Comment, Lecturer, LecturerUserComment, ReviewStatus
Expand Down Expand Up @@ -61,11 +61,10 @@ async def get_lecturer(id: int, info: list[Literal["comments", "mark"]] = Query(
if "comments" in info and approved_comments:
result.comments = approved_comments
if "mark" in info and approved_comments:
result.mark_freebie = sum([comment.mark_freebie for comment in approved_comments]) / len(approved_comments)
result.mark_freebie = sum(comment.mark_freebie for comment in approved_comments) / len(approved_comments)
DaymasS marked this conversation as resolved.
Show resolved Hide resolved
result.mark_kindness = sum(comment.mark_kindness for comment in approved_comments) / len(approved_comments)
result.mark_clarity = sum(comment.mark_clarity for comment in approved_comments) / len(approved_comments)
general_marks = [result.mark_freebie, result.mark_kindness, result.mark_clarity]
result.mark_general = sum(general_marks) / len(general_marks)
result.mark_general = sum(comment.mark_general for comment in approved_comments) / len(approved_comments)
if approved_comments:
result.subjects = list({comment.subject for comment in approved_comments})
return result
Expand All @@ -76,19 +75,20 @@ async def get_lecturers(
limit: int = 10,
offset: int = 0,
info: list[Literal["comments", "mark"]] = Query(default=[]),
order_by: list[Literal["general", '']] = Query(default=[]),
order_by: str = Query(
enum=["mark_kindness", "mark_freebie", "mark_clarity", "mark_general", "last_name"], default="mark_general"
DaymasS marked this conversation as resolved.
Show resolved Hide resolved
),
subject: str = Query(''),
name: str = Query(''),
) -> LecturerGetAll:
"""
Scopes: `["rating.lecturer.read"]`

`limit` - максимальное количество возвращаемых преподавателей

`offset` - нижняя граница получения преподавателей, т.е. если по дефолту первым возвращается преподаватель с условным номером N, то при наличии ненулевого offset будет возвращаться преподаватель с номером N + offset

`order_by` - возможные значения `'general'`.
Если передано `'general'` - возвращается список преподавателей отсортированных по общей оценке
`order_by` - возможные значения `"mark_kindness", "mark_freebie", "mark_clarity", "mark_general", "last_name"`.
Если передано `'last_name'` - возвращается список преподавателей отсортированных по алфавиту по фамилиям
Если передано `'mark_...'` - возвращается список преподавателей отсортированных по конкретной оценке

`info` - возможные значения `'comments'`, `'mark'`.
Если передано `'comments'`, то возвращаются одобренные комментарии к преподавателю.
Expand All @@ -101,15 +101,26 @@ async def get_lecturers(
`name`
Поле для ФИО. Если передано `name` - возвращает всех преподователей, для которых нашлись совпадения с переданной строкой
"""
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()
lecturers_query = (
Lecturer.query(session=db.session)
.outerjoin(Lecturer.comments)
.group_by(Lecturer.id)
.filter(Lecturer.search_by_subject(subject))
.filter(Lecturer.search_by_name(name))
.order_by(
nullslast(func.avg(getattr(Comment, order_by)).desc())
DaymasS marked this conversation as resolved.
Show resolved Hide resolved
Temmmmmo marked this conversation as resolved.
Show resolved Hide resolved
if "mark" in order_by
else getattr(Lecturer, order_by)
)
)

lecturers = lecturers_query.offset(offset).limit(limit).all()
lecturers_count = lecturers_query.group_by(Lecturer.id).count()

if not lecturers:
raise ObjectNotFound(Lecturer, 'all')
result = LecturerGetAll(limit=limit, offset=offset, total=len(lecturers))
for db_lecturer in lecturers[offset : limit + offset]:
result = LecturerGetAll(limit=limit, offset=offset, total=lecturers_count)
for db_lecturer in lecturers:
lecturer_to_result: LecturerGet = LecturerGet.model_validate(db_lecturer)
lecturer_to_result.comments = None
if db_lecturer.comments:
Expand All @@ -130,17 +141,12 @@ async def get_lecturers(
lecturer_to_result.mark_clarity = sum(comment.mark_clarity for comment in approved_comments) / len(
approved_comments
)
general_marks = [
lecturer_to_result.mark_freebie,
lecturer_to_result.mark_kindness,
lecturer_to_result.mark_clarity,
]
lecturer_to_result.mark_general = sum(general_marks) / len(general_marks)
lecturer_to_result.mark_general = sum(comment.mark_general for comment in approved_comments) / len(
approved_comments
)
if approved_comments:
lecturer_to_result.subjects = list({comment.subject for comment in approved_comments})
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))
return result


Expand Down
1 change: 1 addition & 0 deletions rating_api/schemas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class CommentGet(Base):
mark_kindness: int
mark_freebie: int
mark_clarity: int
mark_general: float
lecturer_id: int


Expand Down
Loading