Q:

How to display next record in database by clicking button in Flask?

I'm trying to make Flask application that will display in sequence title and content of articles stored in database by clicking in "Next" button but I don't know what I suppose to do below first "if" statment to fetch only one record from database. My current solutions lead to an error: sqlalchemy.orm.exc.MultipleResultsFound: Multiple rows were found for one()
Here is my code:
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)

And here is home.html file:
<!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>

I will be greatfull for any hints.

A:

You're going to need to pass the index to the form and then use that index for the offset. You probably need to add an orderby as well but I didn't include that here. Something like this:
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)

And in your 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>

You'll also need to handle the case where there is no next result, as it will almost certainly cause an exception in this code.

