3

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?

mortymacs
  • 3,456
  • 3
  • 27
  • 53

1 Answers1

8

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)
  • Can such filtering be done in the raw-sql / core level? say in a dialect where I want to filter and replace specific query types? My specific issue is with datetimes - https://stackoverflow.com/questions/46027152/which-part-of-sqlalchemys-dialect-is-responsible-for-pre-processing-queries – Jay Sep 04 '17 at 03:47