day11:SqlAlchemy ORM

Posted 寻找伯乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day11:SqlAlchemy ORM相关的知识,希望对你有一定的参考价值。

一.外键关联,relationship() 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/python
#coding=utf-8
__author__ = ‘yaobin‘
 
‘‘‘
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。
根据类创建对象,对象转换成SQL,执行SQL。
‘‘‘
 
‘‘‘
relationship() 一对多
relationship(backred)|relationship(back_populates) 双向一对多
‘‘‘
 
 
from sqlalchemy import Table,Column,Integer,ForeignKey,String,create_engine,and_,or_,func,table
from sqlalchemy.orm import relationship,sessionmaker
from sqlalchemy.ext.declarative import declarative_base
 
Base=declarative_base()
 
engine = create_engine("mysql+pymysql://root:[email protected]:3306/test2",echo=False)
 
 
Host2Group = Table(‘host_2_group‘,Base.metadata,
    Column(‘host_id‘,ForeignKey(‘host.id‘),primary_key=True),
    Column(‘group_id‘,ForeignKey(‘group.id‘),primary_key=True),
) #两个列不为空,且唯一
 
 
class Host(Base):
    __tablename__ = ‘host‘
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(64),unique=True,nullable=False)
    ip_addr = Column(String(128),unique=True,nullable=False)
    port = Column(Integer,default=22)
    group_id = Column(Integer,ForeignKey(‘group.id‘))
 
    #group=relationship("Group")
    group=relationship("Group",backref=‘host_list‘) #backref 双向,这里是大写Group,类似反射,
    #group=relationship("Group",back_populates=‘host_list‘)   #back_populates 单向的,Group里面也要有host_list
 
    def __repr__(self):
        return "<id=%s,hostname=%s,ip_addr=%s>" %(self.id,
                                                  self.hostname,
                                                  self.ip_addr)
 
class Group(Base):
    __tablename__=‘group‘
    id=Column(Integer,primary_key=True)
    name=Column(String(64),unique=True,nullable=False)
    #host_list=relationship("Host",back_populates="group")  #back_populates 单向的,Host里面也要有group
    def __repr__(self):
        return "<id=%s,name=%s>" %(self.id,self.name,)
 
 
 
#Base.metadata.create_all(engine) #创建所有表结构 # 寻找Base的所有子类,按照子类的结构在数据库中生成对应的数据表信息
 
if __name__ == ‘__main__‘:
    SessionCls = sessionmaker(bind=engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
    session = SessionCls() #连接的实例
 
 
 
    # #创建组相关信息
    # g1=Group(name=‘group1‘)
    # g2=Group(name=‘group2‘)
    # g3=Group(name=‘group3‘)
    # g4=Group(name=‘group4‘)
    # g5=Group(name=‘group5‘)
    #
    # session.add_all([g1,g2,g3,g4])
    # session.add(g5)
 
 
 
    #往host表里面增加数据,
    #all_groups=session.query(Group).filter().all()  #查找全部组
    #print(‘---all_groups:--->‘,all_groups)
 
    #把全部组查出来
    query_g1=session.query(Group).filter(Group.name==‘group1‘).first()
    query_g2=session.query(Group).filter(Group.name==‘group2‘).first()
    query_g3=session.query(Group).filter(Group.name==‘group3‘).first()
    query_g4=session.query(Group).filter(Group.name==‘group4‘).first()
    query_g5=session.query(Group).filter(Group.name==‘group5‘).first()
 
    # h1 = Host(hostname=‘localhost‘,ip_addr=‘192.168.1.54‘,port=10000,group_id=query_g1.id)
    # h2 = Host(hostname=‘ubuntu‘,ip_addr=‘192.168.1.55‘,port=10001,group_id=query_g2.id)
    h3 = Host(hostname=‘centos6.5‘,ip_addr=‘192.168.1.56‘,port=10002,group_id=query_g3.id)
    h4 = Host(hostname=‘centos7.1‘,ip_addr=‘192.168.1.57‘,port=10003,group_id=query_g4.id)
    h5 = Host(hostname=‘centos7.2‘,ip_addr=‘192.168.1.58‘,port=10004,group_id=query_g5.id)
    h6 = Host(hostname=‘centos5.8‘,ip_addr=‘192.168.1.59‘,port=10005,group_id=query_g2.id)
    h7 = Host(hostname=‘centos6.2‘,ip_addr=‘192.168.1.60‘,port=10006,group_id=query_g5.id)
    #session.add_all([h1,h2])
    #session.add_all([h3,h4,h5]) #往host表增加数据
    #session.add_all([h6,h7])
 
    #把全部主机信息查出来
    query_h1=session.query(Host).filter(Host.hostname==‘localhost‘).first()
    query_h2=session.query(Host).filter(Host.hostname==‘ubuntu‘).first()
    query_h3=session.query(Host).filter(Host.hostname==‘centos6.5‘).first()
    query_h4=session.query(Host).filter(Host.hostname==‘centos7.1‘).first()
    query_h5=session.query(Host).filter(Host.hostname==‘centos7.2‘).first()
 
 
    #通过relationship(),打印主机对应的主机组
    print(‘query_h1---->group_name:‘,query_h1.group.name)
    print(‘query_h2---->group_name:‘,query_h2.group.name)
    print(‘query_h3---->group_name:‘,query_h3.group.name)
    print(‘query_h4---->group_name:‘,query_h4.group.name)
    print(‘query_h5---->group_name:‘,query_h5.group.name)
 
 
    #通过relationship(),打印主机组对应的主机清单
    print(‘group1---->host_list:‘,query_g1.host_list)
    print(‘group2---->host_list:‘,query_g2.host_list)
    print(‘group3---->host_list:‘,query_g3.host_list)
    print(‘group4---->host_list:‘,query_g4.host_list)
    print(‘group5---->host_list:‘,query_g5.host_list)
 
    session.commit()



二.多对多,通过中间表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/python
#coding=utf-8
__author__ = ‘yaobin‘
 
‘‘‘
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。
根据类创建对象,对象转换成SQL,执行SQL。
‘‘‘
 
‘‘‘
没有外键关联了,用中间表,实现多对多
‘‘‘
 
from sqlalchemy import Table,Column,Integer,ForeignKey,String,create_engine,and_,or_,func,table
from sqlalchemy.orm import relationship,sessionmaker
from sqlalchemy.ext.declarative import declarative_base
 
Base=declarative_base()
 
engine = create_engine("mysql+pymysql://root:[email protected]:3306/s12day11",echo=False)
 
 
Host2Group = Table(‘host_2_group‘,Base.metadata,
    Column(‘host_id‘,ForeignKey(‘host.id‘),primary_key=True),
    Column(‘group_id‘,ForeignKey(‘group.id‘),primary_key=True),
) #两个列不为空,且唯一
 
 
class Host(Base):
    __tablename__ = ‘host‘
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(64),unique=True,nullable=False)
    ip_addr = Column(String(128),unique=True,nullable=False)
    port = Column(Integer,default=22)
    groups=relationship(‘Group‘,secondary=Host2Group,backref=‘host_list‘#backref双向,secondary指定中间表,
 
    #group=relationship("Group",backref=‘host_list‘) #backref 双向,这里是大写Group,类似反射,
    #group=relationship("Group",back_populates=‘host_list‘)   #back_populates 单向的,Group里面也要有host_list
 
    def __repr__(self):
        return "<id=%s,hostname=%s,ip_addr=%s>" %(self.id,
                                                  self.hostname,
                                                  self.ip_addr)
 
class Group(Base):
    __tablename__=‘group‘
    id=Column(Integer,primary_key=True)
    name=Column(String(64),unique=True,nullable=False)
    #hosts=relationship("Host")
    #host_list=relationship("Host",back_populates="group")  #back_populates 单向的,Host里面也要有group
    def __repr__(self):
        return "<id=%s,name=%s>" %(self.id,self.name,)
 
 
 
#Base.metadata.create_all(engine) #创建所有表结构 # 寻找Base的所有子类

以上是关于day11:SqlAlchemy ORM的主要内容,如果未能解决你的问题,请参考以下文章

Python_Day13_ORM sqlalchemy

Python学习-day13 SqlAlchemy

Python学习 Day17 Python对Mysql操作和使用ORM框架(SQLAlchemy)

python学习--day12

day13 SQLAlchemy

在 SqlAlchemy ORM 中填充相关表

(c)2006-2024 SYSTEM All Rights Reserved IT常识