Mortezaipo Mortezaipo - 1 year ago 87
Python Question

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

I have a

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

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download