【问题标题】:In SQLAlchemy, how do I create a unique pair?在 SQLAlchemy 中,如何创建一个唯一的对?
【发布时间】:2012-01-07 04:44:52
【问题描述】:
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)

到目前为止,这是我的桌子。如您所见,我正在使用“装饰”方式来定义表格。我想创建一个唯一的密钥,但我的线路不起作用。

如何创建一个独特的配对?

【问题讨论】:

    标签: mysql sql database orm sqlalchemy


    【解决方案1】:

    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'),
                         )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2011-02-17
      • 2015-06-30
      • 1970-01-01
      • 2019-09-06
      • 2020-05-23
      相关资源
      最近更新 更多