LoginSignup
0
1

More than 1 year has passed since last update.

リスト型に対応していないSQLAlchemy(sqlite3)で取り扱う方法

Posted at

FlaskでWEBアプリケーションを作成している最中にデータベースにリスト型で格納したいと思い、方法を探していたところに「sqlite3はリスト型に対応していない」という記事を目の当たりにしました。。。

データベース変えようかなとも思いましたが、
request.form.getlist('___')というコードが存在していた為方法を模索した結果、、、、

1,getlist('')のみだと文字列型のリストとなり、HTML上でfor文を使用して回した際一文字づつの表示となってしまう。
2,JSONを使用した場合に関しても、JSON文字列のリストになる為、for文で回した際一文字づつの表示となってしまう。

最終的に、ワードを繋げたり離したりが可能なjoin,splitを使用しました。

###app.py(格納,取り出し)


@app.route("/create", methods=['GET','POST'])
def create():
    if request.method == 'POST':
        
        name = request.form['name']
      #getlistで複数のデータを取得
        list_before = request.form.getlist('list')
      #データをカンマで繋ぐ
        list = ",".join(list_before)
        
        data = List(name = name, list = list)
        db.session.add(data)
        db.session.commit()
        return redirect('/')

@app.route("/detail")
def detail():
    #今回はデータベースの中身をすべて取り出す
    data_all = List.query.all()
    return render_template('detail.html', data = data_all)

###detail.html(for文で回す)

<!--インスタンスを回す-->
{% for i in data %}
    <!--リスト名を表示-->
    {{ i.name }}
    <!--カンマ区切りで取り出し、listに代入-->
    {% set list = i.list.split(',') %}
    <!--代入したlistを回す-->
    {% for l in list %}
        <!--list内の複数のデータを順番に表示-->
        {{ l }}
    {% endfor %}
{% endif %}

以上です。
joinとsplitはセットで覚えておくといいかもです!
非常に重宝します。。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1