2016-10-22 57 views

回答

3

sqlalchemy event是解決方案!

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 

如果你想指定型號名稱(SQLAlchemy的模型類的名字),如在我的情況下使用「用戶」這樣的:

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

可以這樣過濾的原始SQL /核心層做什麼?說一個方言,我想過濾和替換特定的查詢類型?我的具體問題是日期時間 - https://stackoverflow.com/questions/46027152/which-part-of-sqlalchemys-dialect-is-responsible-for-pre-processing-queries – Jay