Drkcore

10 02 2011 SQLAlchemy Tweet

SQLAlchemyで複数のカラムにUnique制約をかける

declarativeで二つのカラムに対してユニーク制約をかけたい時には__table_args__を使う

class Music(Base):
    __tablename__ = 'music'
    __table_args__ = (UniqueConstraint('title','artist'),{})
    id = Column(Integer, primary_key=True)
    title  = Column(String(128))
    artist = Column(String(128))

class Graph(Base):
    __tablename__ = 'graph'
    __table_args__ = (UniqueConstraint('head','tail'),{})
    id = Column(Integer, primary_key=True)
    head = Column(Integer, ForeignKey('music.id'))
    tail = Column(Integer, ForeignKey('music.id'))

実際に作られたテーブルのスキーマ

CREATE TABLE graph (
    id INTEGER NOT NULL, 
    head INTEGER, 
    tail INTEGER, 
    PRIMARY KEY (id), 
     FOREIGN KEY(head) REFERENCES music (id), 
     UNIQUE (head, tail), 
     FOREIGN KEY(tail) REFERENCES music (id)
);
CREATE TABLE music (
    id INTEGER NOT NULL, 
    title VARCHAR(128), 
    artist VARCHAR(128), 
    PRIMARY KEY (id), 
     UNIQUE (title, artist)
);

About

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

Tag

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

Ad

© kzfm 2003-2021