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()

创新互联建站秉承实现全网价值营销的理念,以专业定制企业官网,网站设计制作、成都网站制作重庆小程序开发,网页设计制作,手机网站制作全网整合营销推广帮助传统企业实现“互联网+”转型升级专业定制企业官网,公司注重人才、技术和管理,汇聚了一批优秀的互联网技术人才,对客户都以感恩的心态奉献自己的专业和所长。


分享文章:sqlalchemy连表
网页网址:http://ybzwz.com/article/ijpodc.html