Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

358
Views
how to filter associated data in flask and Flask-SQLAlchemy?

I have just started learning flask and Flask-SQLAlchemy and created following models:-

User:-

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, db.Sequence('users_id_seq'), primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    created_at = db.Column(db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False)
    updated_at = db.Column(db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False, onupdate=helpers.get_utc_now)

    def __repr__(self):
        return '<User %r>' % self.username

Teacher:-

class Teacher(db.Model):
    __tablename__ = "teachers"
    id = db.Column(db.Integer, db.Sequence("teachers_id_seq"), primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    created_at = db.Column(db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False)
    updated_at = db.Column(
        db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False, onupdate=helpers.get_utc_now
    )

    def __repr__(self):
        return "<Teacher %r>" % self.id

Students:-

class Student(db.Model):
    __tablename__ = 'students'
    id = db.Column(db.Integer, db.Sequence('students_id_seq'), primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created_at = db.Column(db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False)
    updated_at = db.Column(db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False, onupdate=helpers.get_utc_now)

    def __repr__(self):
        return '<Student %r>' % self.id

Assignment:-

class Assignment(db.Model):
    __tablename__ = "assignments"
    id = db.Column(db.Integer, db.Sequence("assignments_id_seq"), primary_key=True)
    student_id = db.Column(db.Integer, db.ForeignKey(Student.id), nullable=False)
    teacher_id = db.Column(db.Integer, db.ForeignKey(Teacher.id), nullable=True)
    content = db.Column(db.Text)
    grade = db.Column(BaseEnum(GradeEnum))
    state = db.Column(BaseEnum(AssignmentStateEnum), default=AssignmentStateEnum.DRAFT, nullable=False)
    created_at = db.Column(db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False)
    updated_at = db.Column(
        db.TIMESTAMP(timezone=True), default=helpers.get_utc_now, nullable=False, onupdate=helpers.get_utc_now
    )

    def __repr__(self):
        return "<Assignment %r>" % self.id

Now in my application an student can create, edit and submit an assignment. And when student submit an assignment, it will submitted to the particular teacher.

When student creates an assignment status field in assignment set to DRAFT, and when he submitted the assignment it will changes to SUBMITTED.

I am totally new to flask and Flask-SQLAlchemy and back-end stuff,and unable to figure out how to fetch assignments submitted to particular teacher.

I have written the following query as well but got wrong result**:-**

got empty data but there are data available in db.

@classmethod  # is written is assignment class
    def get_assignments_by_teacher(cls, teacher_id):
        return cls.filter(cls.teacher_id == teacher_id).all()

from where i am calling this method:-

teacher_assignments = Assignment.get_assignments_by_teacher(p.teacher_id)

Thanks in advance.

Hope to here from you soon.

NOTE:- you can also suggest me better title for this post as well.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If you are trying to query all assignments for a certain teacher, you can achieve this by using sqlalchemy's query function with a filter.

Docs

teacher_assignments = Assignment.query.filter(Assignment.teacher_id == teacher_id).all()

You can also add something called a backref on your teacher model definition like this:

assignments = relationship("Assignment", backref="teacher")

Then, if you have your teacher object, you can access their assignments like this without writing any queries: teacher.assignments

See here for more info on Backref

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!