Conditional filtering in SQLAlchemy Conditional filtering in SQLAlchemy flask flask

Conditional filtering in SQLAlchemy


Try:

import sqlalchemydef custom_filter_statement(category_form, cuisine_form):    if category_form == "1" and cuisine_form == "1":        return sqlalchemy.sql.true()    elif category_form == "1":        return Recipe.category_id == category_form    elif cuisine_form == "1":        return Recipe.cuisine_id == cuisine_form    return sqlalchemy.and_(Recipe.category_id==category_form, Recipe.cuisine_id==cuisine_form)if ingredients_form and any_ingredients in ["1", "2"]:    search_result2 = Recipe.query.filter(        Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),        ~Recipe._allergens.any(Allergen.id.in_(allergens_form)),        custom_filter_statement(category_form, cuisine_form)        ).all()

I suggest renaming variables cuisine_form to cuisine_id etc. cause naming *_form for variables holding id value is quite misleading.

Also literals "1" and "2" should be replaced with constants with proper descriptive names so that it is instantly obvious what these values denote.