我的代码如下:
s = DBSession()
r = s.query(Food, FoodCategory).filter(Food.category_id == FoodCategory.id).first()
此查询引发异常:
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'food.category_id' in result set
我直接在 mysql 数据库中尝试查询,它可以正常工作。 我还打印了 sqlalchey 查询。是的,有相同的标签,“food.category_id as food_category_id”和“food_category.id as food_category_id”。
我怀疑既然这个查询对mysql有效,为什么对sqlalchemy无效
最佳答案
SQLAlchemy 使用结果集中的列名来标识列。为避免冲突,它使用表限定名称标记结果列。在这种情况下,我收集的表名为“food”和“food_category”,因此“food_category_id”仍然有一个标签重叠。这种特定情况的解决方法是使用其中一个类的别名:
fa = aliased(FoodCategory)
s.query(Food, fa).filter(Food.category_id == fa.id).all()
编辑:实际上这里有从 SQLAlchemy 0.7 到 0.8 的回归。 0.7 中的行为稍微好一些,您不会收到错误,但其中一列不会加载,除非您稍后访问它。这个问题是here .不过,我还想考虑在此处添加更多自动别名以克服名称冲突,这可能很棘手。
关于python - InvalidRequestError : Ambiguous column name '***' in result set, 当请求对 mysqldb 有效时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924689/