[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

To give you a slightly more concrete flavor of the ORM model, though, here is a very
quick look at how you might use it to create and process database records in the
SQLObject system. In brief, SQLObject maps:



  • Python classes to database tables

  • Python class instances to rows in the table

  • Python instance attributes to row columns


For example, to create a table, we define it with a class, with class attributes that define
columns, and call its creation method (this code is derived from a more complete ex-
ample at SQLObject’s website):


from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite:/:memory:')

class Person(SQLObject): # class: describes table
first = StringCol() # class attributes: row columns
mid = StringCol(length=1, default=None)
last = StringCol()

Person.createTable() # create a database table

Once created, making an instance automatically inserts a row into the database, and
attribute fetches and assignments are automatically mapped to fetches and updates of
the corresponding table row’s column:


p = Person(first='Bob', last='Smith') # new instance: makes and inserts row
p # prints all attributes by name

p.first # attribute: fetches row column
p.mid = 'M' # attribute: updates record

Existing rows/instances may be fetched by methods calls, and we can assign multiple
columns/attributes with a single update operation:


p2 = Person.get(1) # fetch existing record/instance: p2 is p
p.set(first='Tom', last='Jones') # update two attributes/fields at once

In addition, we can select by column values by creating a query object and executing it:


ts = Person.select(Person.q.first=='Tom') # query: select by column value
list(ts) # run the query: list of instances

tjs = Person.selectBy(first='Tom', last='Jones') # alternative query form (AND)

Naturally, this barely scratches the surface of the available functionality. Even at this
level of complexity, though, this is quite a trick—SQLObject automatically issues all
the SQL required to fetch, store, and query the table and rows implied by the Python
class syntax here. Again, the net effect allows systems to leverage the power of
enterprise-level relational databases, but still use familiar Python class syntax to process
stored data in Python scripts.


ORMs: Object Relational Mappers| 1355
Free download pdf