Berco Beute
Berco Beute

Reputation: 1195

Primary key that is unique over 2 columns in SQLAlchemy

Using SQLAlchemy I'm a bit confused about composite keys (?), uniqueconstraint, primarykeyconstraint, etc. How do I create an class that is unique over 2 columns, and refer to that unique combination? Say each User is unique by his combination of name and email:

class User(Base):
    __tablename__ = 'user'
    name = Column(String)
    email = Column(String)

Should I use UniqueConstraint?:

class User(Base):
    __tablename__ = 'user'
    name = Column(String)
    email = Column(String)
    __table_args__ = (UniqueConstraint(name, email), )

But how do I then refer to a specific user from another class?

Upvotes: 3

Views: 5326

Answers (1)

Berco Beute
Berco Beute

Reputation: 1195

Thanks for the feedback. Turns out adding a primary_key=True to each column automatically creates a composite primary key, meaning the combination must be unique but each column individually doesn't have to be unique. So this suffices:

class User(Base):
    __tablename__ = 'user'
    name = Column(String, primary_key=True)
    email = Column(String, primary_key=True)

Upvotes: 8

Related Questions