Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary key that is unique over 2 columns in SQLAlchemy

Tags:

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?

like image 922
Berco Beute Avatar asked Oct 24 '25 04:10

Berco Beute


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)
like image 177
Berco Beute Avatar answered Oct 27 '25 04:10

Berco Beute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!