1
我正在編寫一個Web應用程序,其中數據庫查詢來自兩個選擇框,一個是關於sex
而另一個是關於class_type
。在我的代碼,我有具有以下形式使用2個選擇標準編寫查詢的更好方法
q = User.query.with_entities(*(getattr(User, col) for col in cols))
而且取決於是否sex
和class_type
被選定爲all
一個基本查詢,我打破的情況如下
if sex=='all' and class_type=='all':
rows = q.all()
elif sex=='all' and class_type!='all':
rows = q.filter_by(class_type=class_type)
elif sex!='all' and class_type=='all':
rows = q.filter_by(sex=sex)
else:
rows = q.filter_by(sex=sex, class_type=class_type)
是否有更好的方法來寫這個邏輯?