from flask import Flask, jsonify, json
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float, func, and_, or_, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
# 连接数据库字符串
DB_URI = "mysql://root:123456@127.0.0.1/pyDemo?charset=utf8mb4"
engine = create_engine(DB_URI)
# 判断是否连接成功
engine.connect()
# 创建ORM
Base = declarative_base(engine)
# 创建回话
session = sessionmaker(engine)()
# 父 表/从表
# user/Article
# 用户
class User(Base):
# 表名字
__tablename__ = 'User'
# 列
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
# articles = relationship('Article')
# 文章
class Article(Base):
# 表名字
__tablename__ = 'article'
# 列
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), default='1111')
content = Column(String(50))
# 设置外键
uid = Column(Integer, ForeignKey('User.id', ondelete="RESTRICT"))
# 取得外键User数据 backref反向定义
author = relationship('User', backref='articles')
# 一对多关系数据查询
# 查找文章的作者 多篇文章对应一个人
article = session.query(Article).first()
print(article.author.username)
# 查找一个用户下的多个文章信息
users = session.query(User).first()
print(users.articles)
更多信息:https://tmspace.cn
网友评论