У меня есть этот монстр оператора if, который я использую для фильтрации результатов из базы данных, но он требует рефакторинга, есть ли способ сделать запросы фильтра условными для переменной?Мне нужно вернуть рецепт, относящийся к каждой категории / кухне, если он имеет идентификатор «1», который находится в моей БД.
if ingredients_form and any_ingredients == "1":
if category_form == "1" and cuisine_form == "1":
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form))
).all()
elif category_form == "1":
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form)),
Recipe.category_id==category_form
).all()
elif cuisine_form == "1":
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form)),
Recipe.cuisine_id==cuisine_form
).all()
else:
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form)),
Recipe.category_id==category_form,
Recipe.cuisine_id==cuisine_form
).all()
elif ingredients_form and any_ingredients == "2":
if category_form == "1" and cuisine_form == "1":
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form))
).all()
elif category_form == "1":
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form)),
Recipe.category_id==category_form
).all()
elif cuisine_form == "1":
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form)),
Recipe.cuisine_id==cuisine_form
).all()
else:
search_result2 = Recipe.query.filter(
Recipe._ingredients.any(Ingredient.id.in_(ingredients_form)),
~Recipe._allergens.any(Allergen.id.in_(allergens_form)),
Recipe.category_id==category_form,
Recipe.cuisine_id==cuisine_form
).all()