endorsement/models.py

51 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',
2018-11-28 14:24:32 +01:00
db.Column('user_id', db.String(80), db.ForeignKey('user.id'), primary_key=True),
2018-07-12 20:56:38 +02:00
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 22:09:10 +02:00
id = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
2018-07-12 20:56:38 +02:00
def to_obj(self):
return {
2018-07-12 22:09:10 +02:00
"id": self.id,
"achievements": [x.to_obj() for x in Achievement.query.filter_by(achieved_by=self.id).all()]
2018-07-12 20:56:38 +02:00
}
2018-07-12 19:45:52 +02:00
def __repr__(self):
2018-07-12 22:09:10 +02:00
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):
2018-07-12 22:09:10 +02:00
return str(self.id)
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-11-28 14:24:32 +01:00
achieved_by = db.Column(db.String(80), db.ForeignKey("user.id"), nullable=False)
2018-07-12 20:56:38 +02:00
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
"achieved_by": self.achieved_by
2018-07-12 20:56:38 +02:00
}
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)
2018-11-28 14:24:32 +01:00