82
98

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.

sqlalchemyチュートリアル

Last updated at Posted at 2017-04-25

sqlalchemy: python製のORM(オブジェクトリレーショナルマッパー)。ORMは、一言でいうと、Relational DataBaseを Python Objectのように扱えるライブラリのことです。

インストール

$ pip install SQLAlchemy

1. データベースをつくる

1. データベースへの接続

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)

echo = True にしておくと 発行される SQLがログで吐かれる

2. ベースクラスをつくる

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

3. テーブルを定義する

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __repr__(self):
        return "<User(name='%s', fullname='%s', password='%s')>" % (
                self.name, self.fullname, self.password)

4. テーブルをつくる

Base.metadata.create_all(engine)

以上まとめると、

database_setup.py
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()


class Restaurant(Base):
    __tablename__ = 'restaurant'

    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        return {
            'name': self.name,
            'id': self.id,
        }


class MenuItem(Base):
    __tablename__ = 'menu_item'

    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }


engine = create_engine('sqlite:///restaurantmenu.db')


Base.metadata.create_all(engine)

2. テーブルにメンバーを追加する

1. database_setup.py内オブジェクトの呼び出し

from sqlalchemy import create_engine
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantMenu.db')
Base.metadata.bind=engine

2. セッションをつくる

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()

3. CRUD操作

#create
new_restaurant = Restaurant(name='Pizza Palace')
session.add(new_restaurant)
session.commit()

#read
session.query(Restaurant).all()

#update
burger = session.query(MenuItem).filter_by(name = 'Burger').one()
burger.price = '$2.99'
session.add(burger)
session.commit()

#delete
ice_cream = session.query(MenuItem).filter_by(name = 'Ice Cream').one()
session.delete(ice_cream)
session.commit()

詳細は公式tutorialを参照。非常によくまとまっています。

82
98
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
82
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?