Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Jérôme Pigeot Avatar asked Feb 01 '11 18:02

Jérôme Pigeot


1 Answers

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.

like image 99
Keith Avatar answered Sep 23 '22 02:09

Keith