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