35 lines
1.3 KiB
Python
35 lines
1.3 KiB
Python
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):
|
|
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):
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
name = db.Column(db.String(128), nullable=False)
|
|
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.achieved_by.name)
|