温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

sqlalchemy连表

发布时间:2020-08-04 03:19:17 来源:网络 阅读:258 作者:leiwenbin627 栏目:编程语言

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI