Jérôme Pigeot
Jérôme Pigeot

Reputation: 2141

Is there something equivalent to django's managers in SQLAlchemy?

I have some SQLAlchemy models (Declarative) and some queries to write like:

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?

Upvotes: 7

Views: 2810

Answers (2)

Rick
Rick

Reputation: 16224

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):
    ........

Upvotes: 1

Keith
Keith

Reputation: 43024

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.

Upvotes: 11

Related Questions