97
105

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flask-SQLAlchemyの使い方

Last updated at Posted at 2017-09-27

Flask-SQLAlchemy: FlaskでSQLALchemyを簡単に扱うための拡張

インストール
$ pip install flask-sqlalchemy

使い方

1. モデルを作る

  • db = flask_sqlalchemy.SQLAlchemy()をつくる
  • db.Modelを継承してモデルをつくる
  • db.Columnでcolumnを定義する
  • db.relationshipでモデル同士を繋ぐ
app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

2. データベースを作る

>>> from app import db
>>> db.create_all()

3. CRUD操作

create

user = User('shinzo', 'shinzo.abe@example.com')
db.session.add(user)
db.session.commit()

read all

users = User.query.all()

read, delete

user = db.session.query(User).filter_by(name='shinzo').first()
db.session.delete(user)
db.session.commit()

read, update

user = db.session.query(User).filter_by(name='shinzo').first()
user.email = 'shinzo.abe@google.com'
db.session.add(user)
db.session.commit()
97
105
1

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
97
105

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?