根据多个相关表选择Rows

时间:2014-10-17 03:43:09

标签: flask flask-sqlalchemy

我有以下型号:

modifiers = db.Table('modifiers',
    db.Column('modifier', db.Integer, db.ForeignKey('modifier.id')),
    db.Column('modified_ingredient', db.Integer, db.ForeignKey('modified_ingredient.id')),
    )

modified_ingredients = db.Table('modified_ingredients',
    db.Column('recipe', db.Integer, db.ForeignKey('recipe.id')),
    db.Column('modified_ingredient', db.Integer, db.ForeignKey('modified_ingredient.id'))
    )

class Recipe(db.Model):
    __tablename__ = 'recipe'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(256))
    description = db.Column(db.Text)
    directions = db.Column(db.Text)
    prep_time = db.Column(db.Integer)
    cook_time = db.Column(db.Integer)
    image = db.Column(db.LargeBinary())
    ingredients = db.relationship('ModifiedIngredient', secondary=modified_ingredients)

class Ingredient(db.Model):
    __tablename__ = 'ingredient'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), index=True, unique=True)
    mod_ing = db.relationship("ModifiedIngredient")

class Modifier(db.Model):
    __tablename__ = 'modifier'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(30), index=True, unique=True)

class ModifiedIngredient(db.Model):
    __tablename__ = 'modified_ingredient'

    id = db.Column(db.Integer, primary_key=True)

    amount = db.Column(db.Integer)
    unit = db.Column(db.String(20))
    ingredient = db.Column(db.Integer, db.ForeignKey('ingredient.id'))
    modifiers = db.relationship('Modifier', secondary=modifiers,
        backref=db.backref('modifiers', lazy='dynamic'), lazy='dynamic')

我试图根据两种或两种以上成分来检索食谱。

我能够使用以下方法检索具有单一成分的食谱:

db.session.query(models.Recipe).join(models.ModifiedIngredient, models.Recipe.ingredients).join(models.Ingredient).filter(models.Ingredient.name == 'garlic')

但是,添加多个过滤器会返回0结果。这是有道理的,它将单一成分与配方相匹配,而且一种成分既不是大蒜又是洋葱。那么,我将如何实现这一目标呢?

1 个答案:

答案 0 :(得分:0)

我找到的解决方案是使用交叉。

使用每个过滤器选项发出多个查询:

q1 = db.session.query(models.Recipe).join(models.ModifiedIngredient, models.Recipe.ingredients).join(models.Ingredient).filter(models.Ingredient.name == 'garlic')

q2 = db.session.query(models.Recipe).join(models.ModifiedIngredient, models.Recipe.ingredients).join(models.Ingredient).filter(models.Ingredient.name == 'onion')

q3 = q1.intersect(q2)

q3将包含所有同时包含'洋葱'和'大蒜'的物品