class Answer(db.Model): tablename = 'answer' id = db.Column(db.Integer, primary_key=True, autoincrement=True) content = db.Column(db.Text, nullable=False) question_id = db.Column(db.Integer,db.ForeignKey('question.id')) author_id = db.Column(db.Integer,db.ForeignKey('user.id')) create_time = db.Column(db.DateTime,default=datetime.now) question = db.relationship('Question',backref=db.backref('answers',order_by=id.desc())) author = db.relationship('User',backref=db.backref('answers'))
@app.route('/add_awswer/',methods=['POST']) def and_awser(): content = request.form.get('answer_content') question_id = request.form.get('question_id')
answer = Answer(content=content)
userId = session['user_id']
user = User.query.filter(User.id == userId).first()
answer.author = user
question = Question.query.filter(Question.id == question_id).first()
answer.question = question
db.session.add(answer)
db.session.commit()
return redirect(url_for('detail',question_id = question_id))
本人菜鸟,我想在模板中获取 Answer 模型中总共有多少条数据
1
peinstrike 2018-04-15 13:08:52 +08:00
Answer.query.count()即可
|
2
tlday 2018-04-15 13:10:15 +08:00
|
3
tlday 2018-04-15 13:17:23 +08:00
一楼的写法似乎会构建一个嵌套查询。见 google 搜索结果的第一个链接的第二个回答的第一个评论。
以及: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#counting |
5
deepred 2018-04-16 08:43:21 +08:00
|