Is there something equivalent to django's managers in SQLAlchemy?
I have some SQLAlchemy models (Declarative) and some queries to write like:
开发者_Go百科Mymodel.query.filter(Mymodel.myfield=='lambda')
Since I have to use the above query several times in my code I would like to do better than repeating it over and over. I know that in django you can do it by putting managers in your models.
Is there something equivalent to django's managers in SQLAlchemy? Or maybe another way to do it?
For common queries I add a class method to a mapped (ORM) class. For example:
class User(object):
@classmethod
def get_by_username(cls, dbsession, username):
return dbsession.query(cls).filter(cls.username==username).one()
The mapped class is essentially the manager.
What I end up doing is creating manager classes. I only implement instance methods on the SA object and wrap anything that fetches/generates queries for lists/etc of model instances on the Mgr class instead.
class MyModelMgr(object):
@staticmethod
def get_something(param):
return MyModel.query.filter(MyModel.somefield==param).all()
class MyModel(Base):
........
精彩评论