python_way day13 sqlalchemy

來源:互聯網
上載者:User

標籤:

sqlalchemy

一對多

多對多

 

1、一對多

 

一、#建立表結構class Host(Base):  #所有的子類都繼承這個基類    #建立表結構    __tablename__ = ‘hosts‘    id = Column(Integer, primary_key=True,autoincrement=True)     hostname = Column(String(64),unique=True,nullable=False)         group_id = Column(Integer,ForeignKey(‘groups.id‘))   #建立外面hosts中的group_id關聯到work_group的id    group = relationship("Group")   #要寫大寫的執行個體名字通過映射的關係 , 能在hosts表中查詢到外鍵表中的其他value
  
def __repr__(self):
        return "<id = %s,jump_user_name=%s>" % (self.id, self.username)
 class Group(Base): __tablename__= ‘groups‘ 
    id
= Column(Integer,primary_key=True) #自動自增,主鍵  
    
name = Column(String(64),unique=True,nullable=False)

Base.metadata.create_all(engine)
#執行上面的sql
圖示: group
鍵
1 web 
 
2 db host hostname   

  外鍵group_id
1   nginx        1
2   mysql       2

這時候我們把host的group_id 和 group.id 做了外部索引鍵關聯
意思就是說我必須有group組,在能建立host組,或者說我們也可以先把host的這是為可以為空白,這樣就可以先填寫host這漲表了

二、#插入資料
第一種插入資料的方法
1、我們可以直接插入host主機
h1 = Host(hostname = "nginx")
h2 = Host(hostname = "mysql")
session.add_all([h1,h2])
session.commit()
2、然後我們再插入group資料

g1 = Group(name = ‘web‘)
g2 = Group(name = ‘db‘)

session.add_all([g1,g2])
session.commit()

3、再做host和group關聯(就是把host的group_id 改下)
g1 = session.query(Group).filter(Group.name == "web").first()      #找出g1的對象
h1 = session.query(Host).filter(Host.hostname==‘nginx‘).update({"group_id":g1.id})
session.commit()

#插入資料時也可以以主動指定外鍵的值,但是不要超過被關聯的鍵的範圍就可以
h1 = Host(hostname = "nginx",group_id = 1)
h2 = Host(hostname = "mysql",group_id = 2)
h3 = Host(hostname = "origer",group_id = 3)  這樣就報錯了



第二種插入資料的方法
先把group表值插進去,然後再插入host表
SessionCls = sessionmaker(bind=engine)
session = SessionCls()


g1 = Group(name = ‘web‘) #先插入group表
g2 = Group(name = ‘db‘)
session.add_all([g1,g2])
#
gw = session.query(Group).filter(Group.name == ‘web‘).first() #不用提交g1就可以在記憶體中查詢到group中對應的資料,
gb = session.query(Group).filter(Group.name == ‘db‘).first()
h1 = Host(hostname = "nginx",group_id = gw.id)            #直接複製給h1使用
h2 = Host(hostname = "mysql",group_id = gb.id)
session.add_all([h1,h2])
session.commit()
三、查詢

1、all 和 first
all()
gw = session.query(Group).all()
print(gw)
[<__main__.Group object at 0x0000003438C3F0F0>, <__main__.Group object at 0x0000003438C3F160>] #拿到了跟Group有關的所有資料,是個列表
print(gw[0].name)   
db
print(gw[0].id)
2

first()
gw = session.query(Group).first()
print(gw)
<__main__.Group object at 0x000000C703531208> #這個就是擷取匹配到的第一個對象
print(gw.name)
db
print(gw.id)
2

2、query()
query中是要查的表,裡面放的是表的類名,這裡也是有2中情況

query(class)
gw = session.query(Group).all()
print(gw)
[<__main__.Group object at 0x000000446E0C1080>, <__main__.Group object at 0x000000446E0C10F0>] #這樣知道的是所有的類對象,是個列表

query(class.args)
gw = session.query(Group.name).all()
print(gw)
[(‘db‘,), (‘web‘,)]

3、連表查詢
SessionCls = sessionmaker(bind=engine)
session = SessionCls()


a、join : inner join
gw = session.query(Group).join(Host).all()
print(gw)
[<__main__.Group object at 0x0000002B1B345860>]
 
b、isouter=True : lelf join 
gw = session.query(Host).join(Group,isouter=True).all()
print(gw)
[hostanme : nginx  -  group_id = 1, hostanme : mysql  -  group_id = 1]

+----+----------+----------+------+------+
| id | hostname | group_id | id | name   |
+----+----------+----------+------+------+
| 1 | nginx    | 1     | 1   | web  |
| 2 | mysql    | 1     | 1   | web  |
+----+----------+----------+------+------+

發現,我們擷取到的只是host表裡的內容,並沒有group中的內容

 

  c、我如果我們想要把host表中和gorup中的內容都擷取到

gw = session.query(Host,Group).join(Group,isouter=True).all()
print(gw)
[(hostanme : nginx  -  group_id = 1, <__main__.Group object at 0x000000B3C53140B8>), (hostanme : mysql  -  group_id = 1, <__main__.Group object at 0x000000B3C53140B8>)]

d、我們想要拿到準確的內容,不要對象怎麼做?
gw = session.query(Host.hostname,Group.name).join(Group,isouter=True).all()
print(gw)
[(‘nginx‘, ‘web‘), (‘mysql‘, ‘web‘)]

 

 

自訂查詢傳回值:

class JumpUser(Base):    __tablename__ = ‘jump_user‘    id = Column(Integer, primary_key=True, autoincrement=True)    username = Column(Integer,unique=True,nullable=False)    passwd = Column(Integer,nullable=False)    groups = relationship("Group",secondary=lambda : JumpUser_2_Group.__table__,backref=‘jumpuser_list‘)    host_list = relationship("HostUser", secondary=lambda: JumpUser_2_HostUser.__table__, backref=‘jumpuser_list‘)    def __repr__(self):        return "<id = %s,jump_user_name=%s>" % (self.id, self.username)

repr中我們使用什麼做傳回值,在查詢時就返回什麼

 

  

 

python_way day13 sqlalchemy

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.