首页 > 解决方案 > 如何通过单击 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>

我会很高兴任何提示。

标签: pythonflasksqlalchemy

解决方案


您需要将索引传递给表单,然后将该索引用于offset. 您可能还需要添加一个orderby,但我没有在这里包含它。像这样的东西:

def index():
    next_item = request.form.get('next_item')
    next_item_index = int(request.form.get('next_item_index', 0))
    data = db.query(column='Nauka').offset(next_item_index).limit(1).all()[0]
    return render_template('home.html',
        data=data,
        next_item_index=next_item_index + 1)

在您的 HTML 中:

<div class="container">
    <h1>{{ data.title }}</h1>
    <p>{{ data.content }}</p>
</div>
<form method="POST" action="/">
    <input type="hidden" name="next_item_index" value="{{ next_item_index }}">
    <button type="submit" name="next_item" class="btn btn-success">Next</button>
</form>

您还需要处理没有下一个结果的情况,因为它几乎肯定会在此代码中导致异常。


推荐阅读