On Tue, Jan 27, 2009 at 6:02 PM, Ross Vandegrift <[email protected]> wrote:

> class Book(object):
>    def __init__(self, title, author):
>        self.title = title
>        self.author = author
>        self.bookmark = None
>
>    def bookmark(self, pageno):
>        self.bookmark = pageno

Any normal methods you define in this class will operate on a single
book record, and it should probably not access the Session directly.
If you want a method that operates on multiple records, you can use a
class method:


    @classmethod
    def get_all(class_):
        q = meta.Session.query(class_).filter_by(user_id=1)
        return q.all()

books = model.Book.get_all()

However, I would return the query object rather than a list, so that
the controller or template can call any of its methods it wants (.all,
.count, etc).  That provides a nice generic API for all these
operations.  However, by exposing the query, you're also tying the
controller/template to SQLAlchemy.  This only matters if you think you
might switch to another database system later.

Creating objects I normally do directly in the controller, and same
for deleting or modifying.  However, you could make class methods for
these too.  Or functions in the model.

You can also make a base class with common methods for your ORM
classes.  One of my applications has this in the meta module:


class ORMClass(object):
    """Base class for all ORM classes."""

    _id_attribute = None

    @classmethod
    def query(class_):
        return Session.query(class_)

    @classmethod
    def get(class_, id):
        return class_.query().get(id)

    def __repr__(self):
        if self._id_attribute:
            value = getattr(self, self._id_attribute)
            if isinstance(value, basestring):
                id_str = " '%s'" % value
            elif isinstance(value, (int, long)):
                id_str = " #%s" % value
            elif value is None:
                id_str = " ''"
            else:
                id_str = " %s" % value
        else:
            id_str = ""
        return "<%s%s>" % (self.__class__.__name__, id_str)


But sometimes I wonder whether such trivial magic as .query and .get
is worth it.

-- 
Mike Orr <[email protected]>

--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to