2011-11-27 8 views
6
class PostsSubscribe(Base): 
    __tablename__ = 'posts_subscribe' 
    id = Column(Integer, primary_key = True) 
    post_id = Column(Integer, ForeignKey('posts_posts.id'), nullable=False) 
    persona_id = Column(Integer, ForeignKey('personas_personas.id'), nullable=False) 

    UniqueConstraint('post_id', 'persona_id') #this doesn't work. 
Base.metadata.create_all(engine) 

これまでの私のテーブルです。ご覧のとおり、私はテーブルを定義するための "解体的"な方法を使用しています。一意のキーを作成したいのですが、私の行は機能しません。SQLAlchemyでは、一意のペアを作成するにはどうすればよいですか?

ユニークなペアを作成するにはどうすればよいですか?

答えて

11

UniqueConstraintは、モデルクラス用ではなく、そのテーブル用である必要があります。あなたはそれを__table_args__することができます:

class PostsSubscribe(Base): 
    __tablename__ = 'posts_subscribe' 
    id = Column(Integer, primary_key = True) 
    post_id = Column(Integer, ForeignKey('posts_posts.id'), nullable=False) 
    persona_id = Column(Integer, ForeignKey('personas_personas.id'), nullable=False) 
    __table_args__ = (UniqueConstraint('post_id', 'persona_id', name='_person_post_uc'), 
        ) 
関連する問題