flask 模型关系一对多的关联

    Python编程 wuya 254次浏览 已收录 0个评论

    模型关系

    • 一对多的关联

    from flask import Flask
    from flask_script import Manager
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate, MigrateCommand
    import os

    app = Flask(__name__)
    manager = Manager(app)
    base_dir = os.path.abspath(os.path.dirname(__file__))
    database_uri = “sqlite:///”+ os.path.join(base_dir, “data.sqlite”)
    #app.config[“SQLALCHEMY_COMMIT_ON_TEARDOWN”] = True
    app.config[“SQLALCHEMY_DATABASE_URI”] = database_uri
    db = SQLAlchemy(app)
    migrate = Migrate(app, db)
    manager.add_command(“db”, MigrateCommand)

    class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True)
    #dynamic(不加载记录,但提供加载记录的查询)
    articles = db.relationship(“Article”, backref=”stu”,lazy=”dynamic”)

    class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    sid = db.Column(db.Integer, db.ForeignKey(“student.id”))

    多对多的关联

    from flask import Flask
    from flask_script import Manager
    from flask_migrate import Migrate,MigrateCommand
    from flask_sqlalchemy import SQLAlchemy
    import os

    app = Flask(__name__)
    manager = Manager(app)
    base_dir = os.path.abspath(os.path.dirname(__file__))
    database_uri = “sqlite:///”+os.path.join(base_dir, “data.sqlite”)
    app.config[“SQLALCHEMY_DATABASE_URI”] = database_uri
    db = SQLAlchemy(app)
    migrate = Migrate(app, db)
    manager.add_command(“db”, MigrateCommand)

    class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True)
    course = db.relationship(“Course”, secondary = “xuankebiao”, backref = db.backref(“students”,lazy=”dynamic”),lazy = “dynamic”)

    class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True)

    #声明中间关联表
    xuankebiao = db.Table(“xuankebiao”,
    db.Column(“student_id”, db.Integer, db.ForeignKey(“student.id”)),
    db.Column(“course_id”, db.Integer, db.ForeignKey(“course.id”)))

    # #添加数据路由
    # @app.route(“/many_many/”)
    # def many_many():
    # s = Student.query.get(1)
    # c = Course.query.get(3)
    # print(s.course)
    # s.course.append(c)
    # return “学生”+s.name+”选了”+c.name

    #查询路由
    @app.route(“/many_many/<id>/”)
    def many_many(id):
    # #通过学生查课程
    # s = Student.query.get(id)
    # course = s.course.all()
    # return “,”.join(c.name for c in course)
    #通过课程找学生
    c = Course.query.get(id)
    #?
    students = c.students.all()
    return “,”.join(s.name for s in students)
    if __name__ == ‘__main__’:
    manager.run()


    学海无涯 , 版权所有丨如未注明 , 均为原创丨转载请注明flask 模型关系一对多的关联
    喜欢 (0)
    发表我的评论
    取消评论
    表情 加粗 删除线 居中 斜体 签到

    Hi,您需要填写昵称和邮箱!

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址