今日の朝活
SQLAlchemyのクイックスタートを実施中。
テーブル定義が簡単に書ける
ORMなので、SQL書かずにテーブルが作成できる。 このようにテーブルを定義すると。
# モデルベースクラスを作成 #Base = declarative_base() と同等(2.0から) class Base(DeclarativeBase): pass # モデルベースを拡張して、ORMのデータクラスを作成 # mapped_columnは2.0からの新機能 class Product(Base): __tablename__ = "product" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(255), nullable=False) cost: Mapped[int] = mapped_column(Integer, nullable=False)
以下のSQLが実行される。
CREATE TABLE product ( id SERIAL NOT NULL, name VARCHAR(255) NOT NULL, cost INTEGER NOT NULL, PRIMARY KEY (id) )
エンジン作成時にecho=Trueで標準出力
# DBエンジンを作成 url = "postgresql://postgres:example@localhost:5432/postgres" engine = create_engine(url, echo=True)
データ登録も簡単
データクラスを作成して、登録用の関数を実行するだけ。
# Insert product1 = Product(name="チョコ", cost=100) product2 = Product(name="ガム", cost=10) session.add_all([product1, product2]) session.commit()
最後に
selectのjoinのところで苦戦中・・・。 ちゃんとマニュアル読むか・・・。