【发布时间】:2018-09-30 05:40:20
【问题描述】:
我在将此 SQL 查询转换为 SQLAlchemy 时遇到问题
SELECT Recipe.id, Recipe.name, AVG(Rating.rating) AS ar FROM Recipe LEFT OUTER JOIN Rating ON Recipe.id = Rating.recipe_id GROUP BY Recipe.id ORDER BY Recipe.id ASC;
我目前有:
session.query(Recipe,func.avg(Rating.rating).label('average')).outerjoin(Rating).filter(Recipe.id == Rating.recipe_id).group_by(Recipe.id).all()
但这会返回与此类似的内容,但缺少没有任何评级的元素:
id | name | ar
----+------------------+--------------------
1 | First Response | 4.0000000000000000
34 | First Response 2 | 3.0000000000000000
当命令行中的 PostgreSQL 查询返回时:
id | name | ar
----+------------------+--------------------
1 | First Response | 4.0000000000000000
34 | First Response 2 | 3.0000000000000000
35 | First Response 2 |
36 | First Response 2 |
这些是我的模型:
class Recipe(Base):
__tablename__ = 'recipe'
id = Column(Integer, primary_key=True)
name = Column(String)
prep_time = Column(Integer)
difficulty = Column(Integer)
vegeterian = Column(Boolean)
user_id = Column(Integer, ForeignKey('user.id'))
ratings = relationship("Rating")
def __repr__(self):
return "<Recipe(name='{}', prep_time='{}', difficulty='{}', vegeterian='{}', user='{}')>".format(
self.name, self.prep_time, self.difficulty, self.vegeterian, self.user_id
)
class Rating(Base):
__tablename__ = 'rating'
id = Column(Integer, primary_key=True)
recipe_id = Column(Integer, ForeignKey('recipe.id'))
rating = Column(Integer)
def __repr__(self):
return "<Rating(name='{}', rating='{}')>".format(self.recipe.name, self.rating)
任何帮助将不胜感激!非常感谢。
【问题讨论】:
标签: python sql python-3.x postgresql sqlalchemy