python - 如何通过单击 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>
我会很高兴任何提示。
解决方案
您需要将索引传递给表单,然后将该索引用于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>
您还需要处理没有下一个结果的情况,因为它几乎肯定会在此代码中导致异常。
推荐阅读
- batch-file - 从字符串中删除子字符串
- android - 在本机反应中为垂直和水平方向添加启动画面
- javascript - 为什么主进程和渲染进程调用的window.maximize()和macos上的动画不一样?
- sql - 如何根据上一个观察日期的某些标准选择最近的观察
- teradata - 代码 = 3504:选定的非聚合值必须是关联组的一部分。输出定向到答案集选项卡
- android - Flutter app gradle 构建异常失败
- ubuntu - 没有 ssh-tunnel 的 vagrant-vm 的 Hotmodule 自动重新加载 chrome
- python - 在 pandas 中创建一个分数列,其值取决于另一列的百分位数
- angular - 如何在光标点动态地将数据添加到 CK 编辑器
- maven - 如何使用 Kubernetes 运行器在 Gitlab 中为 Maven 添加持久卷