您好,登錄后才能下訂單哦!
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()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。