sqlalchemy unique pair of columns

Solutions on MaxInterview for sqlalchemy unique pair of columns by the best coders in the world

showing results for - "sqlalchemy unique pair of columns"
Julián
31 Feb 2020
1# version1: table definition
2mytable = Table('mytable', meta,
3    # ...
4    Column('customer_id', Integer, ForeignKey('customers.customer_id')),
5    Column('location_code', Unicode(10)),
6
7    UniqueConstraint('customer_id', 'location_code', name='uix_1')
8    )
9# or the index, which will ensure uniqueness as well
10Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)
11
12
13# version2: declarative
14class Location(Base):
15    __tablename__ = 'locations'
16    id = Column(Integer, primary_key = True)
17    customer_id = Column(Integer, ForeignKey('customers.customer_id'), nullable=False)
18    location_code = Column(Unicode(10), nullable=False)
19    __table_args__ = (UniqueConstraint('customer_id', 'location_code', name='_customer_location_uc'),
20                     )