V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
TOUJOURSER
V2EX  ›  Python

flask 项目,想获取数据库中的某个表有多少条数据记录该如何实现

  •  
  •   TOUJOURSER · 2018-04-15 12:27:24 +08:00 · 4860 次点击
    这是一个创建于 2175 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 模型中总共有多少条数据

    6 条回复    2018-04-16 10:40:27 +08:00
    peinstrike
        1
    peinstrike  
       2018-04-15 13:08:52 +08:00
    Answer.query.count()即可
    tlday
        2
    tlday  
       2018-04-15 13:10:15 +08:00
    tlday
        3
    tlday  
       2018-04-15 13:17:23 +08:00
    一楼的写法似乎会构建一个嵌套查询。见 google 搜索结果的第一个链接的第二个回答的第一个评论。
    以及: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#counting
    John60676
        4
    John60676  
       2018-04-15 22:57:32 +08:00
    @tlday 2 楼有意思的网站,见识到了
    deepred
        5
    deepred  
       2018-04-16 08:43:21 +08:00
    John60676
        6
    John60676  
       2018-04-16 10:40:27 +08:00
    @deepred 6666
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3055 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:00 · PVG 19:00 · LAX 04:00 · JFK 07:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.