【问题标题】:How to get and store 2 values in one column in database? Python Flask SQLAlchemy如何在数据库的一列中获取和存储 2 个值? Python Flask SQLAlchemy
【发布时间】:2018-05-16 13:18:36
【问题描述】:

我试图在一列中存储 2 个值,但我什至不知道这是否可能。

看起来是这样的。我从 HTML 表单中获取数据,如下所示。它有效。

<form action="{{url_for('newBook')}}" method = 'POST'>
    <p>Choose Language</p>
        <select name=language method="GET" action="/" size="2" multiple> 
        {% for language in languages %}
        <option value= "{{language}}" SELECTED>{{ language }}</option>"
        {% endfor %}
        </select>
    <p><input type='submit' value='Create'></p>
    <a href = "{{url_for('showBooks') }}">Cancel</a>
</form>

但它只在数据库中存储了一个值。

class Book(Base):
    __tablename__ = 'Book'
    language = Column(String(30)) # how change that?

这就是我得到这个值的方式。

languages = ['Polish', 'English']
@app.route('/books/new/', methods=['GET', 'POST'])
def newBook():
    if request.method == 'POST':
        newBook = Book(language = request.form['language']) # how change that?
        session.add(newBook)
        session.commit()
        flash("New Book Added!")
        return redirect(url_for('showBooks'))
    else:
        return render_template('newBook.html', languages=languages)

该代码有效,但我只得到英语或波兰语值。但我希望我有时可以存储两个值。我知道可以使用 request.form.getlist 但我没有找到一个工作示例以及如何将其存储在数据库中。

【问题讨论】:

  • newBook = request.form.getlist('language')。这将返回所有值的列表

标签: python html database flask sqlalchemy


【解决方案1】:

要从一个选择元素中检索多个值,您可以将代码更改为:

languages = ['Polish', 'English']
@app.route('/books/new/', methods=['GET', 'POST'])
def newBook():
    if request.method == 'POST':
        newBooks = request.form.getlist('language') # this returns a list of values
        session.add(newBook)
        session.commit()
        flash("New Book Added!")
        return redirect(url_for('showBooks'))
    else:
        return render_template('newBook.html', languages=languages)

至于将它们存储在数据库中,您可以创建另一个存储语言的表并使用外键链接回您的 Book 表。

【讨论】:

    猜你喜欢
    • 2019-09-15
    • 2015-07-26
    • 2021-11-06
    • 2023-03-26
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多