简体   繁体   中英

Joining two tables with one table having a different foreign key

I'm attempting to join two tables together, however, I keep receving the errors of:

sqlalchemy.exc.InvalidRequestError: Could not find a FROM clause to join from. Tried joining to , but got: Can't find any foreign key relationships between 'recipe' and 'ingredient'.

and

sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'recipe' and 'ingredient'.

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

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

    name = db.Column(db.Text)
    description = db.Column(db.Text)
    directions = db.Column(db.Text)
    prep_time = db.Column(db.String(15))
    cook_time = db.Column(db.String(15))
    image = db.Column(db.Text)
    ingredients = db.relationship('Ingredient', secondary=ingredients)
    credit = db.Column(db.String)

    search_vector = db.Column(TSVectorType('name', 'description', 'directions'))

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

    id = db.Column(db.Integer, primary_key=True)
    original = db.Column(db.Text)
    name = db.Column(db.Integer, db.ForeignKey('ingredient_name.id'))
    amount = db.Column(db.String(10))
    unit = db.Column(db.String(20))
    modifiers = db.Column(db.Text)

    search_vector = db.Column(TSVectorType('original'))

ingredients = db.Table('ingredients',
    db.Column('recipe', db.Integer, db.ForeignKey('recipe.id')),
    db.Column('ingredient', db.Integer, db.ForeignKey('ingredient.id'))
    )

I've tried selecting the items three different ways, all fail with the same error.

try1 = db.session.query(models.Recipe).join(models.Ingredient, secondary=ingredients)
try2 = db.session.query(models.Recipe).join(models.Ingredient)
try3 = db.session.query(models.Recipe).join('ingredients')

It looks similar to the example given for a many-to-many relationship given at http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html The only real difference being that Ingredient has a foreign key, which might be throwing it off? If so, I'm still not sure how to fix that issue.

Thanks

Does one of these work if you explicitly specify the relationship in the join?

db.session.query(models.Recipe).\
    join(models.Ingredient, models.Recipe.ingredients)

db.session.query(models.Recipe).\
    join(models.Recipe.ingredients)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM