sqlalchemy连表-创新互联
fromsqlalchemy.ext.declarativeimportdeclarative_base
fromsqlalchemy importColumn,Integer,String,ForeignKey,UniqueConstraint,Index
fromsqlalchemy.ormimportsessionmaker,relationship
fromsqlalchemy importcreate_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()
classUsers(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)
classFavor(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)
classPerson(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)
# 多对多
classServerToGroup(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')
classGroup(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')
classServer(base):
__tablename__ ='server'
id = Column(Integer,primary_key=True,autoincrement=True)
hostname = Column(String(64),unique=True,nullable=False)
definit_db():
base.metadata.create_all(engine)
defdrop_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()
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
新闻标题:sqlalchemy连表-创新互联
文章链接:http://ybzwz.com/article/dhojhd.html