R
R
Radist_1012016-09-04 05:00:36
Flask
Radist_101, 2016-09-04 05:00:36

Is it possible to override Model.query in SQLAlchemy?

Good day!
How can query be overridden in a SQLAlchemy model? For example, I need to always get active points:
Place.query.filter(Place.is_deleted == False)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2016-09-04
@nirvimel

class CustomQuery(Query):
    def __new__(cls, *args, **kwargs):
        if args and hasattr(args[0][0], "is_deleted"):
            return Query(*args, **kwargs).filter_by(is_deleted=False)
        else:
            return object.__new__(cls)
session = scoped_session(sessionmaker(query_cls=CustomQuery))
Source.
As an alternative, you can create the corresponding VIEW directly in the database:
CREATE VIEW actual_places AS
    SELECT *
    FROM places
    WHERE is_deleted = FALSE;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question