endorsement/models.py

52 lines
1.5 KiB
Python
Raw Normal View History

2018-07-12 19:45:52 +02:00
from app import db
2018-07-12 20:56:38 +02:00
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)
)
2018-07-12 19:45:52 +02:00
class User(db.Model):
2018-07-12 20:56:38 +02:00
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()]
}
2018-07-12 19:45:52 +02:00
def __repr__(self):
return '<User %r>' % self.username
# For login
def is_authenticated(self):
return True
def is_active(self):
return True
def is_admin(self):
return self.admin
def is_anonymous(self):
return False
def get_id(self):
return str(self.username)
2018-07-12 19:45:52 +02:00
class Achievement(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
2018-07-12 20:56:38 +02:00
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
}
2018-07-12 19:45:52 +02:00
def __repr__(self):
2018-07-12 20:56:38 +02:00
return '<Achievement %r from %r>' % (self.name, self.achieved_by.name)