Is there something equivalent to django managers in SQLAlchemy?

I have some SQLAlchemy (declarative) models and some queries for writing 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 it better than repeating it again and again. I know that in django you can do this by putting managers in your models.

Is there something equivalent to django managers in SQLAlchemy? Or maybe another way to do this?

+3
source share
2 answers

For general queries, I add a class method to the mapped (ORM) class. For instance:

class User(object):

    @classmethod
    def get_by_username(cls, dbsession, username):
        return dbsession.query(cls).filter(cls.username==username).one()

.

+8

. SA , / /etc Mgr.

class MyModelMgr(object):
    @staticmethod
    get_something(param):
        return MyModel.query.filter(MyModel.somefield==param).all()

class MyModel(Base):
    ........
+1

Source: https://habr.com/ru/post/1789309/


All Articles