您的位置 首页 python学习笔记

flask 模型关系一对多的关联

模型关系 一对多的关联 from flask import Flask from flask_script import Manager from flask_sqlal…

模型关系

  • 一对多的关联

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()

本文来自网络,不代表立场,转载请注明出处:http://www.zhengzhou888seo.com/3840.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注

联系我们

联系我们

18134416366

在线咨询: QQ交谈

邮箱: 894974231@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部