SQLAlchemy сложные запросы
И так. Встала проблема с запросами в БД через sqlalchemy.
Схема базы данных
Ingredient.py
class Ingredient(Base):
""" Holds all ingredients """
__tablename__ = 'ingredients'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String, unique=True)
def __init__(self, name):
self.name = name
def __repr__(self):
return f"<Ingredient(name={self.name}, id={self.id})>"
Amount.py
class Amount(Base):
""" Holds amounts for ingredients which connected to the recipes table """
__tablename__ = 'amount'
id = Column(Integer, primary_key=True, autoincrement=True)
recipe_id = Column(Integer, ForeignKey(Recipe.id))
ingredient_id = Column(Integer, ForeignKey(Ingredient.id))
amount = Column(Float, default=0.0)
unit = Column(String)
ingredient = relationship('Ingredient')
def __init__(self, recipe_id: int, ingredient_id: int, amount: float, unit: str):
self.recipe_id = recipe_id
self.ingredient_id = ingredient_id
self.amount = amount
self.unit = unit
def __repr__(self):
return f"<Amount(ingredient_id={self.ingredient_id}, amount={self.amount}, recipe_id={self.recipe_id})>"
Recipe.py
class Recipe(Base):
""" Holds recipes info """
__tablename__ = 'recipes'
id = Column(Integer, primary_key=True)
kind = Column(String, default="None")
name = Column(String, unique=True)
time = Column(Integer, default=0)
ingredients = relationship('Amount')
def __init__(self, kind: str, name: str, time: int):
self.kind = kind
self.name = name
self.time = time
def __repr__(self):
return f"<Recipe(name={self.name}, kind={self.kind})>"
Собственно вопросы:
- Как получить все рецепты, в которых содержатся ингредиенты
['a', 'b', 'c'] - Как получить все рецепты, у которых
kind=xи в которых одновременно содержатся['a', 'b', 'c']ингредиенты.
Пытался сам, но из-за relationship в голове бардак.
def get_recipes_by_ingredients(self, ingredients: list, limit=50, kinds=None):
kinds = [] if not kinds else kinds
if limit > 50 or [x for x in kinds if x not in config['kinds']]:
return False
for x in ingredients:
res = self.session.query(Recipe).filter_by(ingredients=) # ?
print(res)