Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

361
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda