V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Apr 15, 2018 · 5687 views
    This topic created in 2945 days ago, the information mentioned may be changed or developed.

    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 replies    2018-04-16 10:40:27 +08:00
    peinstrike
        1
    peinstrike  
       Apr 15, 2018
    Answer.query.count()即可
    tlday
        2
    tlday  
       Apr 15, 2018
    tlday
        3
    tlday  
       Apr 15, 2018
    一楼的写法似乎会构建一个嵌套查询。见 google 搜索结果的第一个链接的第二个回答的第一个评论。
    以及: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#counting
    John60676
        4
    John60676  
       Apr 15, 2018
    @tlday 2 楼有意思的网站,见识到了
    deepred
        5
    deepred  
       Apr 16, 2018
    John60676
        6
    John60676  
       Apr 16, 2018
    @deepred 6666
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4435 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 10:13 · PVG 18:13 · LAX 03:13 · JFK 06:13
    ♥ Do have faith in what you're doing.