Flask 4つの一般的なテンプレート

6758 ワード

自己関連多対多モデルを学習した場合、詳細な資料が見つからず、自分にバックアップします.

一対多の関係

class Role(db.Model):
     __tablename__ = 'roles'
    id= db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role', lazy='dynamic')

class User(db.Model):
    __tablename__ = 'users'  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

多対多関係

tb_student_course = db.Table('tb_student_course',
                             db.Column('student_id', db.Integer, db.ForeignKey('students.id')),
                             db.Column('course_id', db.Integer, db.ForeignKey('courses.id'))
                             )

class Student(db.Model):
    __tablename__ = "students"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

    courses = db.relationship(
        'Course', 
        secondary=tb_student_course,
        backref=db.backref('students', lazy='dynamic'),
        lazy='dynamic'
    )

class Course(db.Model):
    __tablename__ = "courses"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

自己相関ペア数

class Comment(db.Model):
    """ """
    __tablename__ = "comments"

    id = db.Column(db.Integer, primary_key=True)
    #  
    content = db.Column(db.Text, nullable=False)
    #  id
    parent_id = db.Column(db.Integer, db.ForeignKey("comments.id"))
    parent = db.relationship(
        "Comment", 
        remote_side=[id],
        backref=db.backref('childs', lazy='dynamic')
    )

自己相関多対多

tb_user_follows = db.Table(
    "tb_user_follows",
    db.Column('follower_id', db.Integer, db.ForeignKey('info_user.id'), primary_key=True),  #  Id
    db.Column('followed_id', db.Integer, db.ForeignKey('info_user.id'), primary_key=True)  #  id
)

class User(db.Model):
    """ """
    __tablename__ = "info_user"

    id = db.Column(db.Integer, primary_key=True)  
    name = db.Column(db.String(32), unique=True, nullable=False)

    followers = db.relationship(
       'User',
       secondary=tb_user_follows,
       primaryjoin=id == tb_user_follows.c.follower_id,
       secondaryjoin=id == tb_user_follows.c.followed_id,
       backref=db.backref('followed', lazy='dynamic'),
       lazy='dynamic'
     )