Reputation: 4894
I'm working with sqlalchemy, and coming from learning an orm with ruby/rails activerecord and datamapper, it is a bit different.
So, having some models and needing what I think of as class and instance level methods, I see that python does not do this, or the level I understand of python so far does not do this. What is the pythonic way to build new methods for a model: decorators, make a module and import methods, etc? I need to various things so there is no specific coding question, just a general request for guidance on effective ways to handle models with sqlalchemy where model specific methods need to be handled.
Note: this is not an invitation to debate language specifics, I only mention what I've learned so far and how I can take this to application in a new situation.
Upvotes: 3
Views: 3020
Reputation: 43024
You can make model methods as class methods on a model definition. For example:
class User(object):
@classmethod
def get_by_username(cls, dbsession, username):
return dbsession.query(cls).filter(cls.username==username).scalar()
mapper(User, tables.auth_user,
properties={
...
}
)
Allows you to use the class as a container for table specific methods. Like this:
user = User.get_by_username(session, "me")
Upvotes: 10