在SQLAlchemy中,如何创建唯一的对?

TIM*_*MEX 7 mysql sql database orm sqlalchemy

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)
Run Code Online (Sandbox Code Playgroud)

到目前为止这是我的表.如您所见,我正在使用"Declorative"方式定义表格.我想创建一个唯一的键,但我的行不起作用.

如何创建一个独特的对?

van*_*van 12

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'),
                     )
Run Code Online (Sandbox Code Playgroud)