【问题标题】:Queries in Sqlalchemy Flask not returning rowsSqlalchemy Flask 中的查询不返回行
【发布时间】: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


【解决方案1】:
  • 下面的查询将返回books,在其标题中有单词/字符串 keyword
Book.query.filter( Book.title.like("%keyword%") ).all()

在like过滤器中使用keyword作为变量和不是单词/字符串,使用python插值或f-string:

Book.query.filter( Book.title.like('%{}%'.format(keyword)) ).all()
or
Book.query.filter( Book.title.like(f'%{keyword}%') ).all()
  • 要使用or_ (and_, in_ ..) 表达式你需要导入它,参考这个topic
from sqlalchemy import or_

books = Book.query.filter( or_(Book.isbn.like(f'%{keyword}%'), Book.title.like(f'%{keyword}%') )
  • 在search.html

搜索表单通常使用GET方法提交

<!-- Search form -->
<form method="GET" 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>
  • 在search()函数中

由于form 操作是GET,因此路由方法中不需要POST(您甚至可以将其删除,默认为GET 方法)

from markupsafe import escape  # to escape user input and prevent sql injection ..

@app.route("/search")
@login_required
def search():

    keyword = escape(request.form.get("keyword"))  # here
    books = Book.query.filter(Book.title.like(f'%{keyword}%')).all()  # here

    # books is null, if condition is not satisfied
    # if books is None:
    #    return render_template("home.html")

    # return "books" object even it's empty and in your temple check it and display
    # the right message according to it
    return render_template('search.html', title='Search', books=books)
  • 在search.html
{% 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>
{% else %}

  no books with "keyword"

{% endif %}

【讨论】:

  • 所以我也必须从烧瓶中导入逃逸。现在完美运行了,tyvm!
猜你喜欢
  • 1970-01-01
  • 2015-10-18
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 2017-08-23
相关资源
最近更新 更多