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)
到目前为止这是我的表。如您所见,我正在使用“Declorative”方式定义表格。我想创建一个唯一的键,但我的行不起作用。
如何创建唯一的对?
答案 0 :(得分: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'),
)