数据库操作
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
# 连接数据库
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'fk.sqlite')
# 设置sqlalchemy 自动更新
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
# 读取config对象
app.config.form_object(Config)
# 创建对象
db = SQLLAlchemy(app)
# 创建模型
# 学生类
class Student(db.Model):
__tablename__ = 'tb_student'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
name = db.Column(db.String,nullable=False)
age = db.Column(db.String(32),nullable=False)
def __repr__(self):
return '<obj:name:{}>'.format(self.name)
# 老师类
class Teacher(db.Model):
__tablename__='tb_teacher'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
name = db.Column(db.String,nullable=False)
age = db.Column(db.String(32),nullable=False)
# 设置多对多关系
student = db.relationship('Student',secondary=teacher_student,backref='teacher')
def __repr__(self):
return '<obj:name:{}>'.format(self.name)
# 多对多关系类表
teacher_student = bd.Table(
'teacher_student',
db.Column('id',db.Integer,primary_key=True,autoincrement=True)
db.Column('teacher_id',db.Integer,db.ForeignKey='tb_teacher.id')
db.Column('student_id',db.Integer,db.ForeignKey='tb_student.id')
)
# 保存到数据库
if __name__ == '__main__':
db.drop_all()
db.create_all()
# 添加数据
stu1 = Student(name='zs',age=19)
stu2 = Student(name='li',age=23)
stu3 = Student(name='aa',age=34)
tea1 = Teacher(name='lw',age=45)
tea2 = Teacher(name='lz',age=49)
db.session.add_all([stu1,stu2,stu3,tea1,tea2])
db.session.commit()
# 设置关系
tea1.student.append(stu1)
tea1.student.append(stu2)
tea1.student.append(stu3)
tea2.student.append(stu1)
tea2.student.append(stu2)
tea2.student.append(stu3)
# 查询lw教的学生
tea = Teacher.quary.filter(Teacher.name=='lw').first()
stu = tea.student
# 查询zs的所有老师
stu1 = Student.query.filter(Student.name=='zs').first()
tea1 = stu1.teacher
# 解除lw与其学生zs的关系
stu2 = Student.query.filter(Student.name=='zs').first()
tea2 = Teacher.quary.filter(Teacher.name=='lw').first()
tea2.student.remove(stu2)
db.session.commit()
mysql数据库设置
**# mysql 8.0 需要升级SQLAlchemy至最新版**
# 1配置
import os
# 获取绝对路径
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
class Config(object):
# 连接数据库
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/database'
# 设置sqlalchemy 自动更新
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
app = Flask(__name__)
# 读取config对象
app.config.from_object(Config)
if __name__=='__main__':
import pymysql
pymysql.install_as_MySQLdb()