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/10059345/

相关文章:

python - 查询 Pandas 数据框

python - Jupyter Notebook 中没有名为 'graphviz' 的模块

python - 仅比较文件/文件夹名称的目录,打印任何差异?

python - 如何将 sqlalchemy 查询作为字典返回?

mysql - 如何在 sqlalchemy 中进行此查询?

python - 为什么在Python中设置pop返回第一个元素而list pop返回最后一个元素

python - 在 numpy 数组中获取项目的邻居

python - 调用存储函数或过程不会插入和保留更改

python - sqlalchemy 中使用反射和声明性语法的一对多关系定义给出了连接条件错误

python - SQLAlachmey : ORM filter to match all items in a list, 没有