endorsement/models.py
2018-07-12 22:09:10 +02:00

48 lines
1.4 KiB
Python

from app import db
endorsed = db.Table('endorses',
db.Column('user_id', db.String, db.ForeignKey('user.id'), primary_key=True),
db.Column('achievement_id', db.Integer, db.ForeignKey('achievement.id'), primary_key=True)
)
class User(db.Model):
id = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
def to_obj(self):
return {
"id": self.id,
"achievements": [x.to_obj() for x in Achievement.query.filter_by(achieved_by=self.id).all()]
}
def __repr__(self):
return '<User %r>' % self.id
# For login
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.id)
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.id"), 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.id 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)