Flask SQLAlchemy query from heirarchy

108 views Asked by At

I'm using Flask and SQLAlchemy with marshmallow, and trying to work my head around something. If I have several models (tables) that work using Foreign Keys in a heirarchy, how can I properly query a result from the furthest child?

Eg:

class School(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name =  db.Column(db.String(50))

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    school_id = db.Column(db.Integer,db.ForeignKey('school.id'))
    school = db.relationship("School", backref=db.backref("schoola", uselist=False))

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    course_id = db.Column(db.Integer, db.ForeignKey('course.id'))
    course = db.relationship("Course", backref=db.backref("coursea", uselist=False))

I've got Schemas for each in Marshmallow. What I'm looking for here is how I could retrieve all the student information for Students in a particular school (using SQLAlchemy). Later I will serialize these into JSON.

1

There are 1 answers

0
Alex Seifi On BEST ANSWER

I'm not familiar with Marshmallow but I guess you can do something similar to this:

School.query.\
         join(Course).\
         join(Course.schoola).\
         filter(School.name == 'School Name').all()

OR

Student.query \
            .join(Course) \
            .join(School) \
            .filter(School.name == 'School Name')