gpt4 book ai didi

python - 如何通过HTML形式插入到关联表中?

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:35 24 4
gpt4 key购买 nike

尝试重现(以最简单的方式)Maciej Cegłowski 的 http://pinboard.in ;我有书籍和标签,而不是链接和标签。每本 Book 都可以用任意数量的 Tag 进行标记,并且一个 Tag 与许多 Book 相关联

class Book(db.Model):
__tablename__ = 'books'
book_id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(120), unique=True)
auth = db.Column(db.String(120), unique=True)
comment = db.Column(db.String(120), unique=True)
date_read = db.Column(db.DateTime)
era = db.Column(db.String(36))
url = db.Column(db.String(120))
notable = db.Column(db.String(1))

tagged = db.relationship('Tag', secondary=assoc, backref=db.backref('thebooks',lazy='dynamic'))

class Tag(db.Model):
__tablename__ = 'tags'
tag_id = db.Column(db.Integer, primary_key=True)
tag_name = db.Column(db.String(120))

def construct_dict(query):
books_dict = {}
for each in query: # query is {<Book object>, <Tag object>} in the style of assoc table - therefore, must make a dictionary bc of the multiple tags per Book object
book_data = books_dict.setdefault(each[0].book_id, {'bookkey':each[0], 'tagkey':[]}) # query is a list like this {index-book_id, {<Book object>}, {<Tag object #1>, <Tag object #2>, ... }}
book_data['tagkey'].append(each[1])
return books_dict

@app.route('/query')
def query():
query = db.session.query(Book, Tag).outerjoin('tagged') # query to get all books and their tags
books_dict = construct_dict(query)

return render_template("query.html", query=query, books_dict=books_dict)

这是我开始有点迷路的地方;也就是说,构建正确的逻辑来处理我正在尝试做的事情,这将在下面详细描述。

{% for i in books_dict %}  
<a href="{{books_dict[i].bookkey.url}}" target="_blank">{{books_dict[i].bookkey.title}}</a>
{% for i in books_dict[i].tagkey %} # tagkey is a list of Tag objects; for each Book's tagkey, print each Object's tag_name
<a href="/tag/{{i.tag_name}}" class="tag-link">{{i.tag_name}}</a>
{% endfor %}
<a href="" class="edit">edit</a> # eventually, edit link will display the form
<form method="add_tag_to_book">
{% for j in books_dict[i].tagkey %}
<input type="text" name="tag" value="{{j.tag_name}}" />
{% endfor %}
<input type="submit" value="save">
</form>
{% endfor %}

对于任何一本书,用户(现在只有我)应该能够:

  • 更新 assoc 表,以便在 Book 实例和 Tag 实例之间创建一个新的关联;
  • 或者,如果 Tag 不存在,则创建一个新的 Tag 实例(当然,UPDATE assoc 表,以便 Book 实例正确关联新标签)

我认为这项任务对我来说很复杂,因为我仍在努力处理 Jinja 循环中的范围。然而,我意识到我需要做这样的事情:

  1. 获取用户的输入;检查 tag_name 是否已经存在于 __tablename__ = "tags"

  2. 如果 tag_name 已经存在,则获取其 tag_id 以及 Book 实例的 book_id 并将行添加到 assoc 表(即 book_id|tag_id)

  3. 如果tag_name不存在,创建新的Tag()实例,然后执行步骤2

最佳答案

首先,构建book_dict词典:

def construct_dict(query):
books_dict = {}
for each in query: # query is {<Book object>, <Tag object>} in the style of assoc table - therefore, must make a dictionary bc of the multiple tags per Book object
book_data = books_dict.setdefault(each[0].book_id, {'bookkey':each[0], 'tagkey':[]}) # query is a list like this {index-book_id, {<Book object>}, {<Tag object #1>, <Tag object #2>, ... }}
book_data['tagkey'].append(each[1])
return books_dict

@app.route('/query')
def query():
query = db.session.query(Book, Tag).outerjoin('tagged') # query to get all books and their tags
books_dict = construct_dict(query)

return render_template("query.html", query=query, books_dict=books_dict)

然后,除了打印每个Book book_dict 中的实例(并列出与书相关的 Tag 对象),我们为每个 Book 创建一个表单允许用户关联新 Tag 的实例用于 Book :

{% for i in books_dict %}
<a href="{{books_dict[i].bookkey.url}}">{{books_dict[i].bookkey.title}}</a>,
{{books_dict[i].bookkey.auth}}

{% for i in books_dict[i].tagkey %}
<a href="/tag/{{i.tag_name}}" class="tag-link">{{i.tag_name}}</a>
{% endfor %}

<form action="{{ url_for('add_tag_to_book') }}" method=post class="edit-form">
<input type="hidden" name="book_id" value={{books_dict[i].bookkey.book_id}} />
<input type="text" name="tag_name" value="" />
<input type="submit" value="save">
</form>
{% endfor %}

... 可见 <input>将采用用户输入的值,其中有 name="tag_name" ;提交表单时,路线 /add_tag_to_book路线被称为。从表单中,我们获取 book_id (打印在表格中但不可见,即 <input type="hidden" name="book_id" value={{books_dict[i].bookkey.book_id}} /> );我们还获取了 <input> 的值带有 name="tag_name" 的元素):

@app.route('/add_tag_to_book', methods=['POST'])
def add_tag_to_book():
b = request.form['book_id']
t = request.form['tag_name']

接下来,我们应该检查是否tag_name用户提交的已经是一个Tag() ; Python 返回 None如果标签名称​​不Tag 中找到 table ;否则,它将返回 Tag具有 tag_name=t 的对象(即用户提交的tag_name);如果tag_object == None , 我们需要创建 Tag() 的新实例使用 tag_name用户提供:

    tag_object = Tag.query.filter_by(tag_name=t).first()

if tag_object == None:
new_tag = Tag(tag_name=t)
db.session.add(new_tag)
db.session.commit()
tag_object = Tag.query.filter_by(tag_name=t).first()

tag_object_id = tag_object.tag_id

此时,我们将有一个 tag_object (新创建的或以前在我们的 Tag 表中)其 tag_id我们可以抓取并插入到我们的关联表中,连同 book_id对于 Book目的。接下来,我们创建一个数据库连接,插入book_id & tag_id ,提交到数据库,然后将用户返回到 query页:

    conn = db.session.connection()
ins = assoc.insert().values(book_id=b,tag_id=tag_object_id)
result = conn.execute(ins)
db.session.commit()

return redirect(url_for('query'))

将所有内容放在一起,完整的 @app.route('/add_tag_to_book')看起来像这样:

@app.route('/add_tag_to_book', methods=['POST'])
def add_tag_to_book():
b = request.form['book_id']
t = request.form['tag_name']
tag_object = Tag.query.filter_by(tag_name=t).first()

if tag_object == None:
new_tag = Tag(tag_name=t)
db.session.add(new_tag)
db.session.commit()
tag_object = Tag.query.filter_by(tag_name=t).first()

tag_object_id = tag_object.tag_id

conn = db.session.connection()
ins = assoc.insert().values(book_id=b,tag_id=tag_object_id)
result = conn.execute(ins)
db.session.commit()

return redirect(url_for('query'))

关于python - 如何通过HTML形式插入到关联表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com