• 测开之路一百四十三: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()

    运行

    数据库已创建

  • 相关阅读:
    sqlserver字符串拆分(split)方法汇总
    AQS和synchronized
    ReentrantLock和AbstractQueuedSynchronizer
    基于注解实现的策略模式
    堆排序
    无回显下的命令执行判断与利用方式研究
    Linux与windows写入base64编码后的webshell
    使用腾讯云函数上线Cobalt Strike
    javascript实现自适应宽度的瀑布流
    利用iframe实现ajax 跨域通信的解决方案
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11494822.html
Copyright © 2020-2023  润新知