我正在尝试根据用户给出的评分来计算游戏的平均评分。 我的models.py重要部分看起来像这样
class Review(db.Model):
id = db.Column(db.Integer, primary_key=True)
rating = db.Column(db.Numeric(precision=2, scale=1), index=True)
body = db.Column(db.String(140))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
game_id = db.Column(db.Integer, db.ForeignKey('game.id'))
class Game(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), index=True, unique=True)
reviews = db.relationship('Review', backref='game', lazy='dynamic')
def avg_rating(self):
ratings = Review.query.with_entities(Review.rating).filter_by(game_id=self.id).all()
return sum(ratings) / len(ratings)
和routes.py
中games = Game.query.order_by(Game.avg_rating.desc()).all()
但是我得到这个错误
'function' object has no attribute 'desc'
如何获得按平均评分排序的游戏列表?
我将我的models.py avg_rating函数更改为混合属性
@hybrid_property
def avg_rating(self):
total_rating = 0
reviews = Review.query.filter_by(game_id=self.id).all()
for review in reviews:
total_rating += review.rating
return total_rating / len(reviews)
现在我收到此错误
AttributeError: 'decimal.Decimal' object has no attribute 'desc'