Turtles Are Cute
Turtles Are Cute

Reputation: 3426

Simplying SQLalchemy queries

SQLalchemy query syntax is verbose:

models.session.query(models.Person).filter(models.Person.first_name == 'David').all()

I've read several guides implying table objects have query method, but can't find it in the SQLalchemy docs, nor make it work in my code. Is there any reason why I shouldn't use code like below?

class QueryMethod:
    @classmethod
    def filter(cls, *args, **kwargs):
        return session.query(cls).filter(*args, **kwargs).all()


class Person(Base, QueryMethod):
    __tablename__ = 'people'

    id = Column(Integer, primary_key=True)
    first_name = Column(String(255))

New query syntax allowed by this inherritance:

models.Person.filter(models.Person.first_name=='David')

My question: is there a way to remove the 'models.Person' bit inside the filter method call?

Upvotes: 0

Views: 71

Answers (1)

RedBaron
RedBaron

Reputation: 4755

I guess you are looking for filter_by. The query would be something like

session.query(models.Person).filter_by(first_name="foo")

The filter classmethod that you have used harcodes the session. I would recommend that you pass the session explicitly to it so that the same query can be re-used over different sessions.

Upvotes: 1

Related Questions