From 4f2dcd9d93fee3a75b260b2367abd0acf3ad959a Mon Sep 17 00:00:00 2001 From: Robbe Van Herck Date: Thu, 12 Jul 2018 20:56:38 +0200 Subject: [PATCH] Updated models --- models.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/models.py b/models.py index ec6ac76..f199945 100644 --- a/models.py +++ b/models.py @@ -1,20 +1,35 @@ from app import db +endorsed = db.Table('endorses', + db.Column('user_id', db.String, db.ForeignKey('user.username'), primary_key=True), + db.Column('achievement_id', db.Integer, db.ForeignKey('achievement.id'), primary_key=True) +) + class User(db.Model): - __tablename__ = "Users" - id = db.Column(db.Integer, primary_key=True) - username = db.Column(db.String(80), unique=True, nullable=False) - achievements = db.relationship("Achievement", backref="person", lazy=True) - endorses = db.relationship("Achievement", backref="endorsed_by", lazy=True) + username = db.Column(db.String(80), unique=True, nullable=False, primary_key=True) + + def to_obj(self): + return { + "username": self.username, + "achievements": [x.to_obj() for x in Achievement.query.filter_by(achieved_by=self.username).all()] + } def __repr__(self): return '' % self.username class Achievement(db.Model): - __tablename__ = "Achievement" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), nullable=False) - person_id = db.Column(db.Integer, db.ForeignKey("Users.id")) + achieved_by = db.Column(db.Integer, db.ForeignKey("user.username"), nullable=False) + + endorsed_by = db.relationship('User', secondary=endorsed, lazy='subquery', backref=db.backref('user', lazy=True)) + + def to_obj(self): + return { + "id": self.id, + "name": self.name, + "endorsed_by": [x.username for x in self.endorsed_by], # Don't show full user object to avoid infinite loops + } def __repr__(self): - return '' % (self.name, self.person.username) + return '' % (self.name, self.achieved_by.name)