from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine
engine=create_engine("mysql+pymysql://root:123456@192.168.0.6/wupeiqi",max_overflow=1000,
encoding='utf-8',echo=False)#最大连接数1000
base=declarative_base()
class Users(base):
__tablename__='users'
id=Column(Integer,primary_key=True)
name=Column(String(32))
extra=Column(String(16))
__table_args__=(
UniqueConstraint('id','name',name='uix_id_name'),
Index('ix_id_name','name','extra'),
)
def __repr__(self):
return "%s-%s"%(self.id,self.name)
class Favor(base):
__tablename__='favor'
nid=Column(Integer,primary_key=True)
caption=Column(String(50),default='red',unique=True)
def __repr__(self):
return "%s-%s"%(self.nid,self.caption)
class Person(base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=True)
favor_id = Column(Integer, ForeignKey("favor.nid"))#设置favor_id为外键,与favor表的nid关联
# 与生成表结构无关,仅用于查询方便
favor = relationship("Favor", backref='pers')#在计算机内存里Person与Favor建立关联,Person通过favor关键字查询
#Favor里表的内容,而Favor可以通过关键字pers反查Person里表的信息
def __repr__(self):
return "%s-%s"%(self.name,self.favor.caption)
# 多对多
class ServerToGroup(base):
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(Integer, ForeignKey('server.id'))
group_id = Column(Integer, ForeignKey('group.id'))
group = relationship("Group", backref='s2g')
server = relationship("Server", backref='s2g')
class Group(base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False)
port = Column(Integer, default=22)
# group = relationship('Group',secondary=ServerToGroup,backref='host_list')
class Server(base):
__tablename__ = 'server'
id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False)
def init_db():
base.metadata.create_all(engine)
def drop_db():
base.metadata.drop_all(engine)
base.metadata.create_all(engine)#建表
Session=sessionmaker(bind=engine)
session=Session()
obj=Users(name="alex0",extra='sb')
session.add(obj)
session.add_all([
Users(name="alex1",extra='sb'),
Users(name='alex2',extra='sb'),
])
#连表
ret=session.query(Person,Favor).filter(Person.favor_id==Favor.nid).all()
print(ret)
ret1=session.query(Person).join(Favor).all()
print(ret1)
#session.commit()
sqlalchemy连表
原创leiwenbin627 博主文章分类:p12 ©著作权
文章标签 sqlalchemy 连表 文章分类 Python 后端开发
上一篇:sqlalchemy增删改查
下一篇:sqlalchemy_外键连接表
-
sqlalchemy 主从表
一、准备工作:主数据库服务器:OS:Windows Server 2008 R2 DB: SQL Server 2008 R2Hostname : CXMasterDB IP: 192.168.1.224/24  
sqlalchemy 主从表 数据库 数据库服务器 Server -
sqlalchemy 建立表
鉴于许多同学对Qt编译myql总是不能成功,出现各种问题,今天特此写出本教程,希望能够帮到需要的同学。 首先,需要明白编译的目的和原理。 目的:Qt 5.2版本以前都是不带my
sqlalchemy 建立表 Qt mysql #include