В SQLAlchemy, как мне создать уникальную пару? - PullRequest
7 голосов
/ 27 ноября 2011
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)

Пока это мой стол.Как видите, я использую «Деклоративный» способ определения таблиц.Я хочу создать уникальный ключ, но моя линия не работает.

Как создать уникальную пару?

1 Ответ

12 голосов
/ 28 ноября 2011

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'),
                     )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...