Flask-数据库一对多关系

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
# 数据库配置
USERNAME = 'root'
PASSWORD = '123456'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'zz_flask'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOST,
                                                                                             PORT, DATABASE)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 动态跟踪修改设置,如果未设置会弹出警告
app.config['SQLALCHEMY_ECHO'] = True  # 查询时会显示原始的sql语句
db = SQLAlchemy(app)  # 创建实例,读配置参数,将和数据库相关的配置加载到SQLAlchemy对象中



# 一对一的关系,relationship用在一,外键用在多
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(200), nullable=False)
    # 简历relationship属性方法,建立模型关系,第一个参数为多方模型的类名,添加backref可以实现多对一的反向查询
    acles = db.relationship("Article", backref="users")  # 一个人发表多篇文章


class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    # 外键设置:外键的数据类型应参考引用的字段类型
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))  # 表名+字段名


@app.route('/createtable')
def create_table():
    db.create_all()
    return "创建表成功"


# 删除表
@app.route('/droptable')
def droptable():
    db.drop_all()
    return '删除表成功'


@app.route('/add')
def add():
    # 添加两条用户信息
    user1 = User(username="赵景潮")
    user2 = User(username="刘强东")
    user3 = User(username="黄一凡")
    db.session.add(user1)
    db.session.add(user2)
    db.session.add(user3)

    # 添加三条文章信息
    article1 = Article(title="西游记", content="三打白骨精", author_id=1)
    article2 = Article(title="水浒传", content="武松打虎", author_id=2)
    article3 = Article(title="三国演义", content="桃园三结义", author_id=2)
    article4 = Article(title="白蛇", content="白素贞", author_id=3)
    db.session.add(article1)
    db.session.add(article2)
    db.session.add(article3)
    db.session.add(article4)

    db.session.commit()
    return "添加成功"
@app.route('/sel2')
def sel2():
    user=User.query.filter(User.id==2).first()  #查询符合条件的记录
    article=user.acles     #取得user对象的所有acticle属性
    print(article)
    for k in article:      #遍历整个article
        print(k)           #打印输出
        print(k.title)     #打印输出标题
    
    return "查询成功"

if __name__ == '__main__':
    app.run(debug=True)
    #encoding:utf-8

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