删除数据

  • 定义删除author和book的路由
# 删除作者
@app.route('/delete_author/<int:author_id>')
def delete_author(author_id):
    author = Author.query.get(author_id)
    if not author:
        flash('数据不存在')
    else:
        try:
            Book.query.filter_by(author_id=author_id).delete()
            db.session.delete(author)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print e
            flash('操作数据库失败')

    return redirect(url_for('index'))


# 删除书籍
@app.route('/delete_book/<int:book_id>')
def delete_book(book_id):
    book = Book.query.get(book_id)
    if not book:
        flash('数据不存在')
    else:
        try:
            db.session.delete(book)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print e
            flash('操作数据库失败')

    return redirect(url_for('index'))
  • 在模版中添加删除的 a 标签链接
<h2>书籍列表</h2>
<ul>
{% for author in authors %}
    <li>
        {{ author.name }} <a href="/delete_author/{{ author.id }}">删除</a>
        <ul>
            {% for book in author.books %}
                <li>{{ book.name }} <a href="/delete_book/{{ book.id }}">删除</a></li>
            {% else %}
                    <li>无书籍</li>
            {% endfor %}
        </ul>

    </li>
{% endfor %}
</ul>