【发布时间】:2020-07-04 09:46:46
【问题描述】:
所以我试图根据用户搜索的 keyword 查询heroku 中的数据库,但我遇到了问题,它没有给我返回行。
- 当我在下面使用这个查询时,它会给我正确的行。
books = Book.query.filter_by(title=keyword).all()
- 下面这一行给出了错误,
or is not defined但我没有看到问题?
books = Book.query.filter(or_(Book.isbn.like("%keyword%"), Book.title.like("%keyword%")
- 当我在下面使用这些查询时,没有返回任何行:
Book.author.like("%keyword%"))).all()
Book.query.filter(Book.title.like("%keyword%")).all()
在我的search()函数的代码下面
@app.route("/search", methods=['GET', 'POST'])
@login_required
def search():
keyword = request.form.get("keyword")
books = Book.query.filter(Book.title.like("%keyword%")).all()
#books is null, if condition is not satisfied
if books is None:
return render_template("home.html")
return render_template('search.html', title='Search', books=books)
models.py
from flaskblog import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
class Book(db.Model):
__tablename__ = "books"
id = db.Column(db.Integer, primary_key=True)
isbn = db.Column(db.String, nullable=False, unique=True)
title = db.Column(db.String, nullable=False)
author = db.Column(db.String, nullable=False)
year = db.Column(db.Integer, nullable=False)
搜索.html:
{% extends "layout.html" %}
{% block content %}
<div class="col-md-12">
<!-- Search form -->
<form method="post" action="search" class="form-inline d-flex justify-content-center md-form form-sm">
<input class="form-control form-control-sm mr-3 w-75" type="text" name="keyword" placeholder="Search" aria-label="Search">
<i class="fas fa-search" aria-hidden="true"></i>
</form>
</div>
{% if books %}
<div class="row">
<div class="col-sm-8 blog-main">
{% for book in books %}
<div class="blog-post">
<h2 class="blog-post-title"> {{ book.title }}</h2>
<p>
{{ book.isbn }}
</p>
</div>
{% endfor %}
</div>
</div>
{% endif %}
{% endblock content %}
【问题讨论】:
-
SQLAlchemy的
or_函数需要导入,例如from sqlalchemy import or_。你把它导入你的模块了吗? -
@snakecharmerb 不,我没有。现在它没有给出错误,但它也没有返回行。并且这些行确实存在于 db 中,并且与它的连接很好
标签: flask sqlalchemy