如何在Sqlite中删除记录
我正在使用 Flask 的教程应用程序学习 Python,但我不知道如何引用数据库中的特定行。我正在尝试使用模板中的删除链接来删除记录。我花了一整天的时间尝试了我能找到的所有内容并真正理解了这一点。我知道这很简单,但我不明白!
这是 html 模板:
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}
<h2>{{ entry.text|safe }}</h2>
{% if session.logged_in %}
<a href="{{ url_for('delete_entry') }}">Delete</a>
{% endif %}
{% else %}
{% endfor %}
</ul>
如您所见,每个条目旁边都有一个删除链接。我应该如何引用 数据库中的 id 正确吗?
这是我到目前为止拥有的 Python 函数:
@app.route('/delete')
def delete_entry():
if not session.get('logged_in'):
abort(401)
g.db.execute('delete from entries where id=(select max(id)from entries)')
g.db.commit()
flash('The entry was deleted')
return redirect(url_for('show_entries'))
到目前为止我拥有的功能可以工作,但它不是我想要的。提前致谢!
I'm learning Python with the tutorial app from Flask and I can't figure how to reference a certain row in the database. I m trying to delete a record by using the delete link in the template.I spent a whole day trying everything I could find and to really understand this. I know it's simple but I don't get it!
Here's the html template:
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}
<h2>{{ entry.text|safe }}</h2>
{% if session.logged_in %}
<a href="{{ url_for('delete_entry') }}">Delete</a>
{% endif %}
{% else %}
{% endfor %}
</ul>
As you can see, next to each entry there's a delete link.How am I supposed to reference the
right id in the database?
Here's the Python function I have so far:
@app.route('/delete')
def delete_entry():
if not session.get('logged_in'):
abort(401)
g.db.execute('delete from entries where id=(select max(id)from entries)')
g.db.commit()
flash('The entry was deleted')
return redirect(url_for('show_entries'))
What I have so far works but It's not what I want. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Sebastien,delete_entry 函数正在删除数据库中的最后一个条目
where id=(select max(id)from items)
您要做的就是在要删除的 url 中插入一个参数,例如 '/delete/ :id' 其中 id 是要删除的条目的 id,然后更改模板以生成 url,如下所示:
并且还更改删除条目的数据库查询:
Edit1:
我检查了 Flask 文档,以便将变量添加到您的路由中,您必须按如下方式修改路由:
通过这种方式,您可以在Python函数中获取entry_id:
最后,您必须在url_for函数中指定您的条目id:
Sebastien the delete_entry function is deleting the last entry in the db
where id=(select max(id)from entries)
What you have to do is insert a parameter in the url for deletion like '/delete/:id' where the id is the id of the entry you want deleted, then change the template to generate the url as so:
And also change the db query that deletes the entry:
Edit1:
I checked the Flask documentation, in order to get variables into your routes you have to modify the route as follows:
In this way you obtain the entry_id in your python function:
And finally you have to specify your entry id in the url_for function: