SqlAlchemy操作(三)

1.基于SQLALCHEMY建表

from sqlalchemy.ext.declarative import  declarative_base
from sqlalchemy import  Column,Integer,String,ForeignKey
from sqlalchemy.orm import sessionmaker,relationships
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123456@132.232.55.XX:3306/db1",
                       max_overflow =5,encoding="utf-8")
BaseModel
=declarative_base() class Role(BaseModel): __tablename__ ="role" rid =Column(Integer,primary_key=True,autoincrement=True) role_name =Column(String(10)) def __repr__(self): output ="(%s,%s)"%(self.rid,self.role_name) return output class User(BaseModel): __tablename__ = "user" nid =Column(Integer,primary_key=True,autoincrement=True) name =Column(String(10),nullable=False)
  role =Column(Integer,ForeignKey("role.rid"))
def __repr__(self): output="(%s,%s,%s)"%(self.nid,self.name,self.role) return output BaseModel.metadata.create_all(engine)

二、修改表结构: 

 1.安装migrate组件 pip install flask-migrate

三、为表添加数据.

Session =sessionmaker(bind =engine)
session =Session()

#添加角色数据
session.add(Role(role_name = "dba"))
session.add(Role(role_name ="sa"))
session.add(Role(role_name ="net"))

#添加用户数据

session.add_all([
    User(name ="fujiz",role ="1"),
    User(name ="fu",role ="2"),
    User(name ="meng",role ="2"),
    User(name ="bin",role ="3"),
])
session.commit()
session.close()

  |||

  

四、连表查询.

res = session.query(User,Role).join(Role).all() #查询所有用户,及对应的role id
print(res)

 输出结果:[((1,fujiz,1), (1,dba)), ((2,fu,2), (2,sa)), ((3,meng,2), (2,sa)), ((4,bin,3), (3,net))]

res2 =session.query(User,Role.role_name).join(Role).all() #查询所有用户和角色
print(res2)

 输出结果:[((1,fujiz,1), 'dba'), ((2,fu,2), 'sa'), ((3,meng,2), 'sa'), ((4,bin,3), 'net')]

res3 =session.query(User.name,Role.role_name).join(Role,isouter=True).filter(Role.role_name=="sa").all()
#查询所有DBA用户
print(res3)

 输出结果:[('fu', 'sa'), ('meng', 'sa')]

 五、使用relationship添加映射关系

class User(BaseModel):
    __tablename__ = "user"
    nid =Column(Integer,primary_key=True,autoincrement=True)
    name =Column(String(10),nullable=False)
    role =Column(Integer,ForeignKey("role.rid"))
    group=relationship("Role",backref ="uu") #Role为类名.

1.正向查询

res4 =session.query(User).all() #查询所有的用户和角色
print(res4)
for i in res4:
    print(i.name,i.group.role_name)  #此时的i.group 就是role表对应的关系。

输出结果:

[(1,fujiz,1), (2,fu,2), (3,meng,2), (4,bin,3), (5,fujiz,1), (6,fu,2), (7,meng,2), (8,bin,3)]


fujiz dba
fu sa
meng sa
bin net
fujiz dba
fu sa
meng sa
bin net

 

2.反向查询.

res5 =session.query(Role).filter(Role.role_name =="dba").first()
# 查询dba组下的所有用户
print("22",res5.uuu) #此时print的结果为
for i in res5.uuu:
    print(i.name,res5.role_name)

打印结果:

  22 [(1,fujiz,1), (5,fujiz,1), (25,fujiz,1)]
  fujiz dba
  fujiz dba
  fujiz dba

说明

relationship 在user表中创建了新的字段,这个字段只用来存放user表中和role表中的对应关系,在数据库中并不实际存在
正向查找: 先从user表中查到符合name的用户之后,此时结果中已经存在和role表中的对应关系,group对象即role表,所以直接使用obj.group.role_name就可以取出对应的角色
反向查找:relationship参数中backref='uuu',会在role表中的每个字段中加入uuu,而uuu对应的就是本字段在user表中对应的所有用户,所以,obj.uuu.name会取出来用户名
所谓正向和反向查找是对于relationship关系映射所在的表而说,如果通过该表(user表)去查找对应的关系表(role表),就是正向查找,反正通过对应的关系表(role表)去查找该表(user表)即为反向查找。而relationship往往会和ForeignKey共存在一个表中。

六,多对多操作.

https://www.cnblogs.com/pycode/p/mysql-orm.html

原文地址:https://www.cnblogs.com/mengbin0546/p/10151765.html