I want to define two related tables which are student and mentor and their relationship has to be defined through a relationship table student_mentor on a database level. They have to be mapped to Flask app classes using Flask SQLAlchemy library. How can I relate the tables using Flask SQLAlchemy relationship and JOIN student and mentor tables during a query, (I neglected some fields of the tables).
The following are the classes of the models:
student:
class Student(db.Model, Serializer):
id = db.Column(db.Integer, primary_key=True)
#some columns...
mentor:
class Mentor(db.Model, Serializer):
id = db.Column(db.Integer, primary_key=True)
#some columns...
student_mentor
class StudentMentor(db.Model, Serializer):
student_id = db.Column(db.Integer) # id column of student table
mentor_id = db.Column(db.Integer) # id column of mentor table
I am looking forward to achieve my goal with a query of this nature:
query:
students = Student.query.order_by(desc(Student.created_at)).join(Mentor).paginate(page=1, per_page=5, error_out=False)
serialization:
students = json.loads(dumps(Student.serialize_list(students.items), default=str))
serializer:
from sqlalchemy.inspection import inspect
class Serializer(object):
def serialize(self):
return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
@staticmethod
def serialize_list(l):
return [m.serialize() for m in l]