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

 

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

 

目录结构

 

main,入口层

 

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:建表模型

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

 

运行

 

数据库已创建

 

转载于:https://www.cnblogs.com/zhongyehai/p/11494822.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值