Help us understand the problem. What is going on with this article?

Flask-SQLAlchemyの使い方

More than 1 year has passed since last update.

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()
msrks
Computer Scienceと物理が好きです
http://msrks.github.io
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした