接着前面的例子说,我们定义了book_table和author_table,接下来:
1 class Book(object):
2 def __init__(self, title):
3 self.title = title
4 def __repr__(self):
5 return "<Book('%s')>" % self.title
6
7 class Author(object):
8 def __init__(self, name):
9 self.name = name
10 def __repr__(self):
11 return "<Author('%s')>" % self.name
这里我们定义两个类,继承自object,类似JavaBeans或者POJO,这里的__init__方法和__repr__方法不是必须的,只是为了创建对象和输出对象内容比较方便。然后就可以用SQLAlchemy的mapper和sessionmaker来建立映射关系并处理持久和查询等操作:
1 from sqlalchemy.orm import mapper,sessionmaker
2
3 mapper(Book, book_table)
4 mapper(Author, author_table)
5
6 Session = sessionmaker(bind=engine)
7 session = Session()
8
9 gia = Book(u'Groovy in Action')
10 ag = Author(u'Andrew Glover')
11
12 session.add(gia)
13 session.add(ag)
14 session.add_all([Book('Hibernate in Action'), Author('Gavin King')])
15 s_gia = session.query(Book).filter_by(title=u'Groovy in Action').first()
16 s_gia.title =u'Groovy in Action Updated'
17
18 print "[DIRTY]", session.dirty
19
20 session.commit() # or session.rollback()
如果你用过Hibernate,那么这些代码对你来说,理解起来应该没有任何难度。
假如我告诉你,每次都要像这样先定义Table(schema),再定义class,然后用mapper建立对照,是不是有点那啥?SQLAlchemy的开发者们也意识到这一点,所以从0.5开始,SQLAlchemy可以通过sqlalchemy.ext.declarative支持我们实现更紧凑的model/schema定义:
1 from sqlalchemy.schema import Table, Column, ForeignKey, Sequence
2 from sqlalchemy.types import *
3 from sqlalchemy.orm import relation
4 from sqlalchemy.ext.declarative import declarative_base
5
6 Base = declarative_base()
7 metadata = Base.metadata
8
9 bookauthor_table = Table('bookauthor', metadata,
10 Column('book_id', Integer, ForeignKey('book.id'), nullable=False),
11 Column('author_id', Integer, ForeignKey('author.id'), nullable=False),
12 )
13
14 class Book(Base):
15 __tablename__ = 'book'
16 id = Column(Integer, Sequence('seq_pk'), primary_key=True)
17 title = Column(Unicode(255), nullable=False)
18 authors = relation('Author', secondary=bookauthor_table)
19
20
21 class Author(Base):
22 __tablename__ = 'author'
23 id = Column(Integer, Sequence('seq_pk'), primary_key=True)
24 name = Column(Unicode(255), nullable=False)
25 books = relation('Book', secondary=bookauthor_table)
这里我们用到了many-to-many关系,其他的常见用法还包括many-to-one、one-to-many、JOIN、子查询、EXISTS、Lazy/Eager Load、Cascade (all/delete/delete-orphan)等等,大家可以根据需要查阅官方文档。