我有一个User
表,其中包含role
列。角色可以是student
,professor
或admin
。用户表与Course
表有关。
如果关系介于Course
和student
之间,那么它应该是many to many
关系,但如果关系介于Course
和professor
之间,那么它应该是one to many
}。
如何定义两个具有不同角色的表之间的多关系?
用户模型
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(40))
lastname = db.Column(db.String(40))
username = db.Column(db.String(40), nullable=False, unique=True)
password_hash = db.Column(db.String(100), nullable=False)
role = db.Column(db.SmallInteger, nullable=False, default=0)
create_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
update_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
# what should i write instead of bellow lines?
# courses = db.relationship('Course', secondary=student_course, backref='students', lazy='dynamic')
# OR
# courses = db.relationship('Course', backref='teacher', lazy='dynamic')
ROLE_STUDENT = 0
ROLE_PROFESSOR = 1
ROLE_ADMIN = 2
课程模型
class Course(db.Model):
id = db.Column(db.Integer, primary_key=True)
teacher_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
title = db.Column(db.String(120))