Flask中模型models.py

1.MySQL链接

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import pymysql

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:qwer1234@localhost:3306/tttt"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

db = SQLAlchemy(app)

2.创建模型

绑定外键

relationship
绑定关联userlogs = db.relationship('Userlog', backref='user')
ForeignKey
关联主键user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 昵称
    pwd = db.Column(db.String(100))
    email = db.Column(db.String(100), unique=True)  # 邮箱
    phone = db.Column(db.String(100), unique=True)  # 手机号码
    info = db.Column(db.Text)
    face = db.Column(db.String(255), unique=True)  # 头像
    addtime = db.Column(db.DateTime, index=True, default=datetime.now)
    uuid = db.Column(db.String(255), unique=True)  # 唯一标志符
    userlogs = db.relationship('Userlog', backref='user')  # 会员日志外键关系

    def __repr__(self):
        return "" % self.name


class Userlog(db.Model):
    __tablename__ = "userlog"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属会员
    ip = db.Column(db.String(100))
    addtime = db.Column(db.DateTime, index=True, default=datetime.now)  # 登录时间

    def __repr__(self):
        return "" % self.id

3.运行

直接运行models.py,会自动生成模型

if __name__ == '__main__':
    db.create_all()
    # 直接运行models.py,会自动生成模型

添加数据

if __name__ == '__main__':
    user = User(
        name = 'hello',
        pwd = generate_password_hash('123456'),
        email = "[email protected]",
        phone = '13800138000'
    )
    db.session.add(user)
    db.session.commit()
查询结果

你可能感兴趣的:(Flask中模型models.py)