与同一SQLAlchemy模型

时间:2018-01-25 19:53:04

标签: python sqlalchemy

我有一个User表,其中包含role列。角色可以是studentprofessoradmin。用户表与Course表有关。

如果关系介于Coursestudent之间,那么它应该是many to many关系,但如果关系介于Courseprofessor之间,那么它应该是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))

0 个答案:

没有答案