假设我有一个代表位置的类。位置“属于”客户。位置由 unicode 10 字符代码标识。 “位置代码”在特定客户的位置中应该是唯一的。
The two below fields in combination should be unique
customer_id = Column(Integer,ForeignKey('customers.customer_id')
location_code = Column(Unicode(10))
如果我有两个客户,客户“123”和客户“456”。它们都可以有一个名为“main”的位置,但都不能有两个名为 main 的位置。
我可以在业务逻辑中处理这个问题,但我想确保无法在 sqlalchemy 中轻松添加需求。 unique=True 选项似乎只在应用于特定字段时才有效,它会导致整个表只有所有位置的唯一代码。
最佳答案
摘自 documentation 列
的:
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.
由于这些属于表而不属于映射类,因此可以在表定义中声明它们,或者如果在 __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'),
)
关于python - sqlalchemy 在多个列中是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059345/