Flask和18讲 sqlite 创建表和表关联

笔记:

1、安装flask_sqlalchemy

2、配置数据库

2.1>配置sqlite

#数据库位置和名称
app.config['SQLALCHEMY_DATABASE_URI'] = r'sqlite:///./db/test.db'

2.2>配置其它数据库

app.config['SQLALCHEMY_DATABASE_URI'] = r'mysql://myname:[email protected]:8080'

基本格式:别名+驱动://用户名:密码@主机:端口/数据库

2.3>#侦测测数据库的改动

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

2.4>#显示sql语句

app.config['SQLALCHEMY_ECHO'] = True

3、新创建一个文件夹 personal,在文件夹下创建 models.py文件,用于创建表

导入run.py文件中的db

from run import *

#(部门表)

class Name(db.Model):

__tablename__ = 'xxx'

id

name

def __init__(self,name):

self.name = name

def __repr__(self):
        return ""

#员工表

class ...同上

***表关系,表关联**,一对多,一个部门对应多个员工

 # 表关系,外键,员工表关联部门表,取表的id列做外键,department.id为表的id列
department_id = db.Column(db.Integer, db.ForeignKey('department.id')        

#关系,Department是部门表的类名,employee 为员工表名

department = db.relationship('Department', backref=db.backref('employee', lazy='dynamic'))

完整代码:

import sys
from run import db
from datetime import datetime

#创建类
class Department(db.Model):
    """部门"""
    __tablename__ = 'department'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String,unique=True)

    def __init__(self,name):
        self.name = name

    def __repr__(self):
        return '<部门{} : {}>'.format(self.id,self.name)


class Employee(db.Model):
    """员工表"""
    __tablename__ = 'employee'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(50))
    gender = db.Column(db.String)
    job = db.Column(db.String)
    birthdate = db.Column(db.DateTime)
    idcard = db.Column(db.String)
    address = db.Column(db.String)
    salary = db.Column(db.Float)
    release_time = db.Column(db.DateTime)


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

        # 表关系,外键,员工表关联部门表,取表的id列做外键
    department_id = db.Column(db.Integer, db.ForeignKey('department.id'))
    department = db.relationship('Department', backref=db.backref('employees', lazy='dynamic'))

    def __repr__(self):
        return '<员工 {}:{} {} {}>'.format(self.id,self.name,self.salary,self.address)

4、控制台常用命令操作:

在查询命令前需要先导入文件:

from run import *
from personal.models import *

查询前员工表10行记录:
for emp in db.session.query(Employee).all()[:10]:
    print(emp)

你可能感兴趣的:(flask,python)