Updated models

This commit is contained in:
Robbe Van Herck 2018-07-12 20:56:38 +02:00
parent f7d7a97c82
commit 4f2dcd9d93
No known key found for this signature in database
GPG key ID: 4D1C8E8FBD1C7188

View file

@ -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 '<User %r>' % 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 '<Achievement %r from %r>' % (self.name, self.person.username)
return '<Achievement %r from %r>' % (self.name, self.achieved_by.name)