better way to write queries with 2 selection criteria
<p>I am writing a web app where database query comes from two selection boxes, one is about <code>sex</code> and the other is about <code>class_type</code>. In my code, I have a base query which has the following form</p>

<pre><code>q = User.query.with_entities(*(getattr(User, col) for col in cols))    
</code></pre>

<p>And depending on whether <code>sex</code> and <code>class_type</code> are chosen to be <code>all</code>, I break the cases as follows</p>

<pre><code>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)
</code></pre>

<p>Is there a better way to write this logic?</p>

<p>You could do this:</p>

<pre><code>filters = {}
if sex != 'all':
    filters['sex'] = sex
if class_type != 'all':
    filters['class_type'] = class_type
rows = q.filter_by(**filters)
</code></pre>

<p>You would only need one condition per attribute, and an empty dictionary for <code>filters</code> would result in a query with no <code>WHERE</code> clause.</p>

python sql sqlalchemy flask-sqlalchemy