Drkcore

25 02 2013 Python SQLAlchemy Tweet

最近覚えたSQLAlchemyのTips

先週は、レガシーなOracleデータベースと格闘していた(文字エンコーディングの件もその一つ)。

__table__と__tablename__の違い

__table__は適切に設定済みのテーブルに対して使うらしい。自分でごちゃごちゃと設定したい場合は__tablename__と__table_args__を使うべし

  • How to override a column name in sqlalchemy using reflection and descriptive syntax

複合プライマリーキーでのone-to-many

主キーが複合プライマリーキーの場合はそれぞれにprimary_key=Trueをつけるが、外部キーで一対多の関連付けをしたい場合には __table_args__で外部キー設定をしておく。

class Protocol(Base):
    __tablename__ = 'tblprotocol'
    id = Column("id", String(32), primary_key=True)
    version = Column("version", String(11), primary_key=True)
    name = Column("name", String(255))

class Experiment(Base):
    __tablename__ = 'tblexperiments'
    __table_args__ = (ForeignKeyConstraint(['protocolid','protocolversion'],
                                      ['tblprotocol.id', 'tblprotocol.version']), {})
    id = Column("id", String(32), primary_key=True)
    protocolid = Column("protocolid", String(32))
    protocolversion = Column("protocolversion", String(11))
    name = Column("name", String(255))
    protocol = relationship("Protocol", backref="experiments")

そもそも主キーの無いテーブル

主キーの無いテーブルはエラーが出るので、適当に複合キーを設定してプライマリーキーにしてしまう。

  • SQLAlchemy declarative: table without any primary keys?
  • I have a schema where my table doesnt have a primary key, can SA's ORM handle it?

その他

SQLもORマッパーもわかっていればバランスの取れた設計になっていいのではなかろうかと思った。ORマッパー側から考えたほうがER図が綺麗になりそうだし。

ProductName 達人に学ぶ SQL徹底指南書 (CodeZine BOOKS)
ミック
翔泳社 / 2520円 ( 2008-02-07 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021