sqlalchemy unique across multiple columns

前端 未结 2 1952
天命终不由人
天命终不由人 2020-11-27 10:41

Let\'s say that I have a class that represents locations. Locations \"belong\" to customers. Locations are identified by a unicode 10 character code. The \"location code\" s

相关标签:
2条回答
  • 2020-11-27 11:28

    Extract from the documentation of the Column:

    unique – When True, indicates that this column contains a unique constraint, or if index is True as well, indicates that the Index should be created with the unique flag. To specify multiple columns in the constraint/index or to specify an explicit name, use the UniqueConstraint or Index constructs explicitly.

    As these belong to a Table and not to a mapped Class, one declares those in the table definition, or if using declarative as in the __table_args__:

    # version1: table definition
    mytable = Table('mytable', meta,
        # ...
        Column('customer_id', Integer, ForeignKey('customers.customer_id')),
        Column('location_code', Unicode(10)),
    
        UniqueConstraint('customer_id', 'location_code', name='uix_1')
        )
    # or the index, which will ensure uniqueness as well
    Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)
    
    
    # version2: declarative
    class Location(Base):
        __tablename__ = 'locations'
        id = Column(Integer, primary_key = True)
        customer_id = Column(Integer, ForeignKey('customers.customer_id'), nullable=False)
        location_code = Column(Unicode(10), nullable=False)
        __table_args__ = (UniqueConstraint('customer_id', 'location_code', name='_customer_location_uc'),
                         )
    
    0 讨论(0)
  • 2020-11-27 11:28
    from flask_sqlalchemy import SQLAlchemy
    db = SQLAlchemy()
    
    class Location(Base):
          __table_args__ = (
            # this can be db.PrimaryKeyConstraint if you want it to be a primary key
            db.UniqueConstraint('customer_id', 'location_code'),
          )
          customer_id = Column(Integer,ForeignKey('customers.customer_id')
          location_code = Column(Unicode(10))
    
    0 讨论(0)
提交回复
热议问题