python之SQLAlchemy

TOP1资料(SQLAlchemy使用笔记--SQLAlchemy ORM)

http://blog.csdn.net/billvsme/article/details/50319471

【知识细节】

http://www.aspku.com/tech/jiaoben/python/51435.html


数据库操作——略复杂,涉及join\outer\outerjoin等

down_bindings = (
    context.session.query(RouterL3AgentBinding).
    join(agents_db.Agent).
    filter(agents_db.Agent.heartbeat_timestamp < cutoff,
           agents_db.Agent.admin_state_up).
    outerjoin(l3_attrs_db.RouterExtraAttributes,
              l3_attrs_db.RouterExtraAttributes.router_id ==
              RouterL3AgentBinding.router_id).
    filter(sa.or_(l3_attrs_db.RouterExtraAttributes.ha == sql.false(),
                  l3_attrs_db.RouterExtraAttributes.ha == sql.null())))


1、数据库间的依赖关系

(1)、Join介绍包含外键

如此处RouterL3AgentBinding包含外键agents_db.Agent,如果需要通过外键过滤需要用到join加入——待确认!


(2)、outerjoin

此处应该是过滤RouterL3AgentBinding数据库外面再套一层对RouterExtraAttributes数据库的过滤;



2、数据库中的orm外键——对应关系

此部分转自:http://www.68idc.cn/help/jiabenmake/python/20150130199786.html

orm可以将数据库存储的数据封装成对象,同时,如果封装的好的话,所有的数据库操作都可以封装到对象中。这样的代码在组织结构上会非常的清晰,并且相对与使用sql语句在sql注入方面会极具降低。

SQLAlchemy中的映射关系有四种,分别是一对多,多对一,一对一,多对多

实现这种映射关系只需要外键(ForeignKey),和relationship

一对多:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, CHAR
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class Parent(Base):
    __table__ = "parent"
    id = Column(Integer, Primary_key=True)
    name = Column(CHAR(50))
    child = relationship("child", backref="parent")
class Child(Base):
    __table__ = "child"
    id = Column(Integer, Primary_key=True)
    name = Column(CHAR(50))
    parent_id = Column(Integer,ForeignKey('parent.id'))

多对一

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, CHAR
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class Parent(Base):
    __table__ = "parent"
    id = Column(Integer, Primary_key=True)
    name = Column(CHAR(50))
class Child(Base):
    __table__ = "child"
    id = Column(Integer, Primary_key=True)
    name = Column(CHAR(50))
    parent_id = Column(Integer,ForeignKey('parent.id'))
    parent = relationship("parent", backref="child")

由此可见,一对多与多对一的区别在于其关联(relationship)的属性在多的一方还是一的一方;如果relationship和ForeignKey都定义在多的一方,那就是多对一,如果relationship定义在一的一方那就是一对多。

多对一来说:

relationship相当于给Child实例增加了一parent属性,在查询过程中,要查询一个Child所关联的所有Parent,可以这样做:

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
def get_engine():
    engine = create_engine("mysql://User:Password@Host/Database?charset=utf8")
_MARK = None
def get_session(autocommit=True, expire_on_commit=False):
    global _MARK
    if _MARK is None:
        Session = sessionmaker(bind=get_engine(),\
            autocommit = autocommit,\
            expire_on_commit = expire_on_commit)
        _MARK = Session()
    return _MARK
def model_query(*args, **kwargs):
    session = kwargs.get("session") or get_session()
    return session.query(*args)
model_query(Child).filter(Child.id=1).parent

backref相当于给Parent实例增加了一个child属性,在查询过程中,如果要查询一个Parent所关联对所有Child,可以这样做:

model_query(Parent).filter(Parent.id=1).child



【其他】:

常见的各类查询命令:http://www.cnblogs.com/kramer/p/4014782.html

入门介绍:http://www.cnblogs.com/booolee/archive/2009/08/26/1554525.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值