码迷,mamicode.com
首页 > 编程语言 > 详细

【13】Python应用系列--ORM

时间:2016-08-05 23:00:30      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

DB First

通过类和对象操作数据库

Code First

  •  自定义生成表
class 类(base):
     列1
     列2
根据类创建表
  • 使用类操作表
session.query(类)

1. 创建单表,一对多

rom sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship

engine = create_engine("mysql+pymysql://root@192.168.101.11:3306/s13", max_overflow=5)

Base = declarative_base()

# 单表
# 创建表
class Test(Base):
    __tablename__ = ‘test‘  # 表名
    nid = Column(Integer, primary_key=True, autoincrement=True) # 创建列
    name = Column(String(32))   # 创建列


# 一对多
# 创建表
class Group(Base):
    __tablename__ = ‘group‘  # 表名
    nid = Column(Integer, primary_key=True, autoincrement=True) # 创建列
    caption = Column(String(32))   # 创建列


# 创建表
class User(Base):
    __tablename__ = ‘user‘  # 表名
    nid = Column(Integer, primary_key=True, autoincrement=True) # 创建列
    name = Column(String(32))   # 创建列
    group_id = Column(Integer, ForeignKey(‘group.nid‘))  # 外键ForeignKey,group表的nid列

    # 输出
    def __repr__(self):
        pass
    def __str__(self):
        pass

def init_db():
    Base.metadata.create_all(engine)

def drop_db():
    Base.metadata.drop_all(engine)
init_db()

2. 连表查询(一对多)

# # 新方式(正向查询)
ret = session.query(User).all()
for obj in ret:
    # obj代指user表的每一行数据
    # obj.group代指group对象
    print(obj.nid, obj.username, obj.group_id, obj.group, obj.group.nid, obj.group.caption)

# 原始方式
ret = session.query(User.username, Group.caption).join(Group, isouter=True).filter(Group.caption == ‘DBA‘).all()
print(ret)
# 新方式(反向查询)
obj = session.query(Group).filter(Group.caption == ‘DBA‘).first()
print(obj.nid)
print(obj.caption)
print(obj.uuu)

3. 多对多查询

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship

engine = create_engine("mysql+pymysql://root@192.168.101.11:3306/s13", max_overflow=5)
Base = declarative_base()


# 创建表
class Host(Base):
    __tablename__ = ‘host‘
    nid = Column(Integer, primary_key=True,autoincrement=True)
    hostname = Column(String(32))
    port = Column(String(32))
    ip = Column(String(32))

class HostUser(Base):
    __tablename__ = ‘host_user‘
    nid = Column(Integer, primary_key=True,autoincrement=True)
    username = Column(String(32))

class HostToHostUser(Base):
    __tablename__ = ‘host_to_host_user‘
    nid = Column(Integer, primary_key=True,autoincrement=True)

    host_id = Column(Integer,ForeignKey(‘host.nid‘))
    host_user_id = Column(Integer,ForeignKey(‘host_user.nid‘))

# 创建表
def init_db():
    Base.metadata.create_all(engine)
# 删除表
def drop_db():
    Base.metadata.drop_all(engine)

init_db()

# 模拟环境数据
Session = sessionmaker(bind=engine)
session = Session()

sion.add_all([
    Host(hostname=‘c1‘,port=‘22‘,ip=‘1.1.1.1‘),
    Host(hostname=‘c2‘,port=‘22‘,ip=‘1.1.1.2‘),
    Host(hostname=‘c3‘,port=‘22‘,ip=‘1.1.1.3‘),
    Host(hostname=‘c4‘,port=‘22‘,ip=‘1.1.1.4‘),
    Host(hostname=‘c5‘,port=‘22‘,ip=‘1.1.1.5‘),
])
session.commit()


session.add_all([
    HostUser(username=‘root‘),
    HostUser(username=‘db‘),
    HostUser(username=‘nb‘),
    HostUser(username=‘sb‘),
])
session.commit()

session.add_all([
    HostToHostUser(host_id=1,host_user_id=1),
    HostToHostUser(host_id=1,host_user_id=2),
    HostToHostUser(host_id=1,host_user_id=3),
    HostToHostUser(host_id=2,host_user_id=2),
    HostToHostUser(host_id=2,host_user_id=4),
    HostToHostUser(host_id=2,host_user_id=3),
])
session.commit()

### 需求:服务器c1的用户

# 查找主机为c1的服务器ID
host_obj = session.query(Host).filter(Host.hostname == ‘c1‘).first()
# print(host_obj.nid)

# 根据服务器ID查找c1上的用户ID
host_2_host_user = session.query(HostToHostUser.host_user_id).filter(HostToHostUser.host_id == host_obj.nid).all()
# print(host_2_host_user)

# 处理用户ID信息
r = zip(*host_2_host_user)
# print(list(r)[0])

# 查找对应用户ID的用户
users = session.query(HostUser.username).filter(HostUser.nid.in_(list(r)[0])).all()

多对多查询:新方法

# 多对多查询
class Host(Base):
    __tablename__ = ‘host‘
    nid = Column(Integer, primary_key=True,autoincrement=True)
    hostname = Column(String(32))
    port = Column(String(32))
    ip = Column(String(32))

class HostUser(Base):
    __tablename__ = ‘host_user‘
    nid = Column(Integer, primary_key=True,autoincrement=True)
    username = Column(String(32))

class HostToHostUser(Base):
    __tablename__ = ‘host_to_host_user‘
    nid = Column(Integer, primary_key=True,autoincrement=True)

    host_id = Column(Integer,ForeignKey(‘host.nid‘))
    host_user_id = Column(Integer,ForeignKey(‘host_user.nid‘))

    host = relationship("Host", backref=‘h‘)
    host_user = relationship("HostUser", backref=‘u‘)

host_obj = session.query(Host).filter(Host.hostname==‘c1‘).first()


for item in host_obj.h:
    print(item.host_user.username)

4. 小结

  • 创建表
  • 操作表
    • 单表
    • 连表:
      • .join
      • 关系  
        • 一对多:fk,关系
        • 多对多:多一张表 fk, fk
        •            关系表:关系
        •            A:关系,(B,AB)

 

【13】Python应用系列--ORM

标签:

原文地址:http://www.cnblogs.com/liangdalong/p/5742807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!