On Tue, Jan 27, 2009 at 05:42:48PM -0800, John Brennan wrote:
> I'm trying encapulate all data stuff in the model. For example, I
> have a Book object so it would have methods like get, get_all, recent,
> etc. Those all work fine, but the problem occurs when trying to
> create a new Book object.
>
>
> /models/book.py:
> class Book(object):
> def get_all(self):
> query = meta.Session.query(Book).filter_by(user_id=1)
> return query.all()
> def save(self):
> meta.Session.save_or_update(self)
> meta.Session.commit()
[snip]
> I can see that maybe the model can't save itself and instead the
> session should be saving it. But how do I go about doing that using
> this modular structure?
SA treats your model object (ie, the class that encapsulates the logic
of your application) separately from the Session (ie, the class that
encapsulates information on how to save and restore persistent data
for object instances).
I think of it like this: a Book object should keep properties about
itself - the title, author, publication data, editon, etc. But a Book
is not the kind of object that saves and loads things to a database. [1]
The SA Session is the kind of object that saves and loads things from
a database. You setup mappers so that SA knows what to save. I would
implement your object like this:
class Book(object):
def __init__(self, title, author):
self.title = title
self.author = author
self.bookmark = None
def bookmark(self, pageno):
self.bookmark = pageno
There's no database code in there, just Book code. Here's the
database table information:
import sqlalchemy as sa
book_table = sa.Table(Column('id', sa.Integer, primary_key=True),
Column('title', sa.Unicode()),
Column('author', sa.Unicode()))
Finally, you need an ORM mapper to link the two up:
import sqlalchemy.orm as orm
book_mapper = orm.mapper(Book, book_table)
Then, in the pylons controller actions, I would do things like this:
class SomeController(BaseController):
def action(self):
q = meta.Session.query(model.Book)
c.paine = q.filter_by(author="Thomas Paine")
c.jefferson = q.filter_by(author="Thomas Jefferson")
return render("/showbooks.mako")
(where showbook.mako iterates over those books and displays some
interesting information about what's in the database).
[1] At least, I have never seen such a book :)
--
Ross Vandegrift
[email protected]
"If the fight gets hot, the songs get hotter. If the going gets tough,
the songs get tougher."
--Woody Guthrie
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---