Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 391
TIMEX Avatar asked Nov 27 '11 04:11

TIMEX


People also ask

How do I make a column unique in SQLAlchemy?

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.

How do I create a many to many relationship in SQLAlchemy?

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.

How do you query a one to many relationship in flask?

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.


1 Answers

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'),
                     )
like image 125
van Avatar answered Oct 02 '22 02:10

van