删除数据
@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'))
<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>