title: JOIN Query Flask SQLAlchemy Related Tables using relationships table
body: <p>I want to define two related tables which are <strong>student</strong> and <strong>mentor</strong> and their relationship has to be defined through a relationship table <strong>student_mentor</strong> 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 <strong>relationship</strong> and JOIN <strong>student</strong> and <strong>mentor</strong> tables during a query, (I neglected some fields of the tables).</p>
  <p>The following are the classes of the models:</p>
  <p><strong>student</strong>:</p>
  <pre><code>class Student(db.Model, Serializer):
    id = db.Column(db.Integer, primary_key=True)
    #some columns...
  </code></pre>
  <p><strong>mentor</strong>:</p>
  <pre><code>class Mentor(db.Model, Serializer):
    id = db.Column(db.Integer, primary_key=True)
    #some columns...
  </code></pre>
  <p><strong>student_mentor</strong></p>
  <pre><code>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
  </code></pre>
  <p>I am looking forward to achieve my goal with a query of this nature:</p>
  <p><strong>query</strong>:</p>
  <pre><code>students = Student.query.order_by(desc(Student.created_at)).join(Mentor).paginate(page=1, per_page=5, error_out=False)
  </code></pre>
  <p><strong>serialization</strong>:</p>
  <pre><code>students = json.loads(dumps(Student.serialize_list(students.items), default=str))
  </code></pre>
  <p><strong>serializer</strong>:</p>
  <pre><code>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]
  </code></pre>