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 so far. As you can see, I'm using the "Declorative" way of defining tables. I want to create a unique key , but my line doesn't work.
How do I create a unique pair?
unique – When True, indicates that this column contains a unique constraint, or if index is True as well, indicates that the Index should be created with the unique flag. To specify multiple columns in the constraint/index or to specify an explicit name, use the UniqueConstraint or Index constructs explicitly.
Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.
The comments class attribute defines a One-to-Many relationship between the Post model and the Comment model. You use the db. relationship() method, passing it the name of the comments model ( Comment in this case). You use the backref parameter to add a back reference that behaves like a column to the Comment model.
UniqueConstraint
should be not for a model class, but for its table. You can you __table_args__
to do that:
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'),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With