0

I want to find all books with the same category as a given book. Right now, my query includes the specific book as well, but I only want other books. How do I exclude the specific book from the query?

@app.route('/book/<id>')
def book(id):
    return render_template(
        'book.html',
        specific_book=Book.query.filter_by(id=id).first(),
        category_books=Book.query.filter_by(category=(Book.query.filter_by(id=id).first()).category).limit(9)
    )

1 Answer 1

1

Add a filter to your query to exclude that id.

@app.route('/book/<id>')
def book(id):
    book = Book.query.get_or_404(id)
    related = Book.query.filter(Book.id != id, Book.category == book.category)
    return render_template('book.html', book=book, related=related)

filter_by is just a shortcut for equality filters, where kwargs are converted to attributes on the current selectable. If you need something besides equality (such as inequality), you use the normal filter method.

This is described in the SQLAlchemy docs' tutorial on queries.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.