How to set up One2many relationships in Flask SQLAlchemy
class Class(db.Model):
id = db.Column(db.Integer, primary_key=True)
students = db.relationship('Students', backref='class')
def as_dict(self):
result = {col.name: getattr(self, col.name) for col in self.__table__.columns}
# add students data to result dict
result['students'] = [student.as_dict() for student in self.students]
return result
class Students(db.Model):
id = db.Column(db.Integer, primary_key=True)
class_id = db.Column(db.Integer, db.ForeignKey('class.id'))
def as_dict(self):
result = {col.name: getattr(self, col.name) for col in self.__table__.columns}
return result