Reputation: 299
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)
)
Upvotes: 0
Views: 1337
Reputation: 127180
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.
Upvotes: 1