猿问

如何通过单击 Flask 中的按钮显示数据库中的下一条记录?

我正在尝试制作 Flask 应用程序,该应用程序将通过单击“下一步”按钮按顺序显示存储在数据库中的文章的标题和内容,但我不知道我想在第一个“if”语句下面做什么以仅获取一条记录从数据库。我当前的解决方案导致错误:sqlalchemy.orm.exc.MultipleResultsFound: Multiple rows were found for one()


这是我的代码:


flask import Flask, render_template, url_for, request

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////PATH/TO/DATABASE/KORPUS/Database.db'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


class Polityka(db.Model):

    __tablename__ = 'polityka_articles'

    id = db.Column('id', db.Integer, primary_key=True)

    title = db.Column('article_title', db.Unicode)

    content = db.Column('article_content', db.Unicode)


@app.route('/', methods=['GET', 'POST'])


def index():


    next_item = request.form.get('next_item')

    data = Database.query.filter_by(column = 'Nauka').first()


    if next_item is not None:

        data = Polityka.query.filter_by(column = 'Nauka').one()

    return render_template('home.html', item_title = data.title, item_content = data.content)



if __name__ == '__main__':

    app.run(debug=True)

这是home.html文件:


<!DOCTYPE html>

<html>

<head>

    <!-- Required meta tag and CSS -->

    <title>Site</title>

</head>

<body>

    <div class='container'>


        <h1>{{ item_title }}</h1>

        <p>{{ item_content }}</p>


    </div>

    <form method="POST" action="/">

        <button type="submit" name="next_item" class="btn btn-success">Next</button>

    </form>

</body>

</html>

我会很高兴得到任何提示。


慕码人2483693
浏览 375回答 1
1回答

30秒到达战场

您将需要将索引传递给表单,然后将该索引用于offset. 您可能还需要添加一个orderby,但我没有在这里添加。像这样的东西:def index():&nbsp; &nbsp; next_item = request.form.get('next_item')&nbsp; &nbsp; next_item_index = int(request.form.get('next_item_index', 0))&nbsp; &nbsp; data = db.query(column='Nauka').offset(next_item_index).limit(1).all()[0]&nbsp; &nbsp; return render_template('home.html',&nbsp; &nbsp; &nbsp; &nbsp; data=data,&nbsp; &nbsp; &nbsp; &nbsp; next_item_index=next_item_index + 1)在你的 HTML 中:<div class="container">&nbsp; &nbsp; <h1>{{ data.title }}</h1>&nbsp; &nbsp; <p>{{ data.content }}</p></div><form method="POST" action="/">&nbsp; &nbsp; <input type="hidden" name="next_item_index" value="{{ next_item_index }}">&nbsp; &nbsp; <button type="submit" name="next_item" class="btn btn-success">Next</button></form>您还需要处理没有下一个结果的情况,因为它几乎肯定会在此代码中导致异常。
随时随地看视频慕课网APP

相关分类

Python
我要回答