您的位置:首页 > 编程语言 > Python开发

采用python中SQLalchemy模块访问数据库(三)

2012-10-12 00:08 423 查看
采用python中SQLalchemy模块访问数据库(三)

上一篇中结合SQLAlchemy中ORM部分实现一个Mapper对象,将类的实例对应表中的记录,实例的属性对应字段。实现一个Data Mapping需要三个元素:Tabella Metadata, user-defined class, mapper对象,这三个是实现对象对表映射的基本元素,在此基础上,可实现一对多的映射,实现类似多表查询的问题

首先创建两个相关联的表Student, Score,表Score中以主表的id字段为外键

Student = Table('student', engine,
column(‘id', Interger, primary_key = True),
column('name', String, nullable=False),
column('age', Interger)
)
Score = Table('score', engine,
column('id', Integer, primary_key=True),
column('student_id', Integer, ForeignKey(student.id))
column('category', String, nullable=False),
column('score', Integer)
)

两表中,Score表以Student表中id项为外键,一般称Student表为主表,Score表为从表

表创建好后,那同样,在python中需定义两个与表相对应的类

class student_type(object):
def __init__(self):
self.name = None
class score_type(object):
def __init__(self):
self.category = None

在建立mapping时,我们只需要体现两个表间又相互关联关系,

并不关心表中具体的主键与外键等关系(由SQLAlchemy处理),

当需要体现表student与表score间的关联关系,mapper具体的定义方法如:

mapper(student_type, student, properties={'_scores': relation(score_type, Score)})

通过properties中参数,实现score_type 与Score的映射,

由此可以通过访问student中的'_scores'属性来查询Score表中的值

另外,properties是一个字典,可以添加多个属性,SQLAlchemy中有些模块如backref, 也可导入

综上,使用关系映射可以方便地从一个对象直接找到相对应的其他的对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息