Many-to-One Relationship Sqlalchemy

I’m working on a new project called brainStorm. It is essentially a fancy todo list. You can create different sessions, add users and vote on items. In the process, I learned about mapping relationships between items. In the below code, “Unranked” refers to each idea and “Score” refers to each score. There are potentially multiple scores for each item. The relationship indicator is included in the child table. We include the unranked_id and mark it as a foreign key and then specify the unranked as a relationship. This will allow you to pull the Score data through the Unranked table.

#model.py
class Unranked(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    session = db.Column(db.Integer, nullable=False)
    name = db.Column(db.String, nullable=False)
    avg_score = db.Column(db.Numeric(3,1), default=None)

    def json_view(self):
        return {"id": self.id, "session": self.session, "name": self.name, "score": str(self.avg_score)}

class Score(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    unranked_id = db.Column(db.Integer, db.ForeignKey('unranked.id'))
    unranked = db.relationship('Unranked',backref=db.backref('scores',lazy='dynamic'))
    user_id = db.Column(db.Integer, nullable=False)
    score = db.Column(db.Integer, nullable=False)

#views.py
def update_average(idea_id):
	idea = Unranked.query.filter_by(id=idea_id).first()
	scores_q = idea.scores.all()
	scores = [score.score for score in scores_q]
	idea.avg_score = sum(scores)/float(len(scores))
	db.session.commit()