sqlalchemy在多个列中是唯一的

Omi*_*nus 149 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))
Run Code Online (Sandbox Code Playgroud)

因此,如果我有两个客户,客户"123"和客户"456".它们都可以有一个名为"main"的位置,但两个位置都不能称为main.

我可以在业务逻辑中处理这个问题,但我想确保无法在sqlalchemy中轻松添加需求.unique = True选项似乎仅在应用于特定字段时才起作用,并且会导致整个表只有所有位置的唯一代码.

van*_*van 257

从以下文档中摘录Column:

unique - 如果为True,则表示此列包含唯一约束,或者如果index也为True,则表示应使用唯一标志创建索引.要在约束/索引中指定多个列或指定显式名称,请显式使用 UniqueConstraintIndex构造.

由于这些属于表而不属于映射类,因此可以在表定义中声明它们,或者如果在以下情况下使用声明性__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'),
                     )
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但我的问题是:您是否使用SA(和Flask)创建数据库架构,还是单独创建它? (2认同)
  • @Smiley `.c.` 是 `.columns.` 的快捷方式。 (2认同)

joa*_*ash 22

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))
Run Code Online (Sandbox Code Playgroud)

  • 必须是 `__table_args__ = (db.UniqueConstraint('customer_id', 'location_code'),)`,不要忘记末尾的逗号。 (14认同)
  • 对于任何想知道为什么有逗号的人来说,`(42)` 与 `42` 相同:括号对单个值没有影响。然而,`(42,)` 是单个元素元组的简写:`(42,) == tuple([42])`。 (2认同)