【发布时间】:2018-03-21 07:56:09
【问题描述】:
Flask Web 开发新手:我正在尝试使用 SQLAlchemy 作为我在 Flask 应用程序中的 ORM 来查询 MySQL 数据库。
每次有 GET 请求时,都会从 python 函数生成一个分数,并以 JSON 格式将总分数(即“点”列的总和)返回给模板。
使用 sum func 时出现“TypeError: 'BaseQuery' object is not callable”:
all_points = [Play.query(func.sum(Play.points))]
当我尝试使用 .get() 时,它会在模板中显示一些时髦的东西(即对象对象],[对象对象]),但至少它会返回一些东西:
all_points = [Play.query.get(1)]
不确定我的错误是什么:查询错误还是我将对象添加到数据库的方式不正确?
//数据库模型
class Play(db.Model):
__tablename__ = "scoring"
rounds = db.Column(db.Integer, primary_key=True)
points = db.Column(db.Integer)
def __init__(self, points):
self.points = points
//棉花糖模式:
class PlaySchema(ma.Schema):
class Meta:
fields = ('rounds','points')
play_schema = PlaySchema()
plays_schema = PlaySchema(many=True,only=('rounds', 'points'))
//从这个函数返回分数:
score = dice_score(d1,d2,d3,d4,d5)
//对于数据库的每个 GET 请求条目为:
db.create_all()
round_score = Play(score)
db.session.add(round_score)
db.session.commit()
//有问题的查询:
all_points = [Play.query(func.sum(Play.points))]
//最后将结果用dump (marshmallow)传递给模板:
dump_score = plays_schema.dump(all_points)
return render_template('main.html',data_get=data_get)
【问题讨论】:
标签: python mysql flask flask-sqlalchemy