In SQLAlchemy, how do I create a unique pair?

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) 

This is my table. As you can see, I use the "Declorative" way of defining tables. I want to create a unique key, but my line is not working.

How to create a unique pair?

+6
source share
1 answer

UniqueConstraint should not be for the model class, but for its table. You can __table_args__ do this:

 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'), ) 
+11
source

Source: https://habr.com/ru/post/902468/


All Articles