Primary key that is unique over 2 columns in SQLAlchemy

Viewed 1312

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?

1 Answers

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)
Related