python - sqlalchemy 跨多列唯一

标签 python sqlalchemy

假设我有一个表示位置的类。位置“属于”客户。位置由 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/30779466/

相关文章:

python - 使用 ORM、声明式样式和关联对象在 SQLAlchemy 中递归选择(深度有限)关系

Python IDLE 卡住

python - 使用 re (雷鬼) 在 python 中查找模式

python - 从 Binance-API (Python) 计算时间戳之外的日期

python - SQLalchemy Primaryjoin 属性在 Python 3.4 中不起作用(使用 Python 2.7 起作用)

python - SQLAlchemy 映射以列出相关对象

python - 有条件地加入 Jinja 中的字符串列表

python - 如何在 python 中制作华夫饼图表? (方形饼图)

python - 类型错误 : can't compare offset-naive and offset-aware datetimes

python - SQLAlchemy 返回元组而不是字典