测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

时间:2022-09-18 12:05:24

基于前一篇内容,可以使用模型的结构

目录结构

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

main,入口层

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

from flask import Flask
from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # 初始化app app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./db/test.db' # 声明数据库类型和地址
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 跟踪改变
app.config['SQLALCHEMY_ECHO'] = True # 打印对应的sql,此操作用sql是怎么样的
db = SQLAlchemy(app) # 创建数据库核心对象并把数据库和app关联起来 if __name__ == '__main__':
app.run(
debug=True
)

models:建表模型

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

from datetime import datetime
from main import db class Department(db.Model):
""" 部门 """
__tablename__ = 'department'
# primary_key=True:主键, autoincrement=True:自动递增
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), unique=True) def __init__(self, name):
self.name = name def __repr__(self):
return f'部门{self.id},{self.name}' class Employee(db.Model):
""" 员工 """
__tablename__ = 'employee'
# primary_key=True:主键, autoincrement=True:自动递增
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
gender = db.Column(db.String)
job = db.Column(db.String)
birthdate = db.Column(db.Date)
idcard = db.Column(db.String)
address = db.Column(db.String)
salary = db.Column(db.Float)
release_time = db.Column(db.DateTime) # 外键: db.Column(db.Integer, db.ForeignKey(表名))
department_id = db.Column(db.Integer, db.ForeignKey('department.id')) # 声明是外键,为department表的id字段 # db.relationship('Department', backref=db.backref('employee', lazy='dynamic'))
# db.relationship(主键类名, backref=引用属性名, lazy='dynamic'))
# lazy:延迟查询:dynamic:动态、select、subquery、joined
department = db.relationship('Department', backref=db.backref('employee', lazy='dynamic')) # 类与表的关系 def __init__(self, name, gender, job, birthdate, idcard, address, salary, release_time=None):
self.name = name
self.gender = gender
self.job = job
self.birthdate = birthdate
self.idcard = idcard
self.address = address
self.salary = salary
self.release_time = release_time if release_time else datetime.now() def __repr__(self):
return f'员工:{self.id} {self.name} {self.salary} {self.address}' if __name__ == '__main__':
db.create_all()

运行

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

数据库已创建

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建

测开之路一百四十三:ORM框架之SQLAlchemy模型及表创建