简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM