Mortezaipo Mortezaipo - 1 month ago 8
Python Question

How to implement a default condition in all SQLAlchemy's queries

I have a

is_deleted
field in all tables which shows that this record has been removed (but it exists in tables).

So how to ignore (never consider)
is_deleted=True
records in all queries in SQLAlchemy?

Answer

the sqlalchemy event is the solution!

from sqlalchemy.orm.query import Query
from sqlalchemy import event

@event.listens_for(Query, "before_compile", retval=True)
def no_deleted(query):
    for desc in query.column_descriptions:
        entity = desc['entity']
        if entity:
            query = query.filter(entity.is_deleted == False)

    return query

if you want specify model name(sqlalchemy model class name) such as 'User' in my case use this:

if entity == 'User':
    query = query.filter(entity.is_verified == True)