Sqlalchemy one to many relationship join?

折月煮酒 提交于 2019-12-05 20:19:17

Your tables and relationships are setup correctly. Your query needs a change.

The reason for an error is the fact that you try to perform a join on the column (Food_Categories.food_categories) instead of a Table (or mapped model object). Technically, you should replace your query with the one below to fix the error:

results = Food.query.join(Food_Categories).all()

This will fix the error, but will not generate the SQL statement you desire, because it will return instances of Food only as a result even though there is a join.

In order to build a query which will generate exactly the SQL statement you have in mind:

results = (db.session.query(Food._id, Food.food_name,
        Food_Categories.food_categories,)
    .join(Food_Categories)).all()
for x in results:
    # print(x)
    print(x._id, x.food_name, x.food_categories)

Please note that in this case the results are not instances of Food, but rather tuples with 3 column values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!