from sqlalchemy.sql import text from flask_sqlalchemy import BaseQuery from ..dependencies import db from ..base.models import Person, Base from ..base.utils import order_by_column_name class Group(Base): __tablename__ = "groups" name = db.Column(db.String(60), nullable=False) project_supervisor_id = db.Column(db.Integer, db.ForeignKey('project_supervisors.id')) project_supervisor = db.relationship('ProjectSupervisor', backref='groups', lazy=True) points_for_first_term = db.Column(db.Integer, default=0, nullable=False) points_for_second_term = db.Column(db.Integer, default=0, nullable=False) class Student(Person): __tablename__ = "students" index = db.Column(db.Integer, primary_key=True) group_id = db.Column(db.Integer, db.ForeignKey('groups.id')) group = db.relationship('Group', backref='students', lazy=True) mode = db.Column(db.Boolean, default=True, nullable=False) # True - stationary, False - non-stationary @classmethod def search_by_fullname_and_mode_and_order_by_first_name_or_last_name(cls, fullname: str = None, mode: bool = None, order_by_first_name: str = None, order_by_last_name: str = None) -> BaseQuery: student_query = cls.query if mode is None: mode = True student_query = student_query.filter_by(mode=mode) if fullname is not None: """This works only for sqlite3 database - concat function doesn't exist so i used builtin concat operator specific only for sqlite db - || """ student_query = student_query.filter( text("students_first_name || ' ' || students_last_name LIKE :fullname ") ).params(fullname=f'{fullname}%') student_query = order_by_column_name(student_query, Student.first_name, order_by_first_name) student_query = order_by_column_name(student_query, Student.last_name, order_by_last_name) return student_query