【问题标题】:sqlalchemy unique across multiple columnssqlalchemy 在多个列中是唯一的
【发布时间】:2012-04-21 00:11:07
【问题描述】:

假设我有一个代表位置的类。位置“属于”客户。位置由 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 选项似乎仅在应用于特定字段时才有效,它会导致整个表只有所有位置的唯一代码。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    documentationColumn 中提取:

    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'),
                         )
    

    【讨论】:

    • 我也面临同样的问题,但使用 UniqueConstraint 并没有帮助我。在我尝试使用 Index('...') 之后,我得到了一个唯一的约束。这种行为有什么解释吗?
    • @swdev: 你使用哪个 RDBMS?
    • 谢谢,但我的问题是:您是使用 SA(和 Flask)创建数据库架构,还是单独创建?
    • 为什么是.c。用过吗?
    • @Smiley .c..columns. 的快捷方式
    【解决方案2】:
    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))
    

    【讨论】:

    • 必须是__table_args__ = (db.UniqueConstraint('customer_id', 'location_code'),),别忘了最后的逗号。
    • 对于任何想知道为什么有那个逗号的人,(42)42 相同:括号对单个值无效。但是,(42,) 是单个元素的元组的简写:(42,) == tuple([42])
    • 这是我唯一能找到这个问题答案的地方!!谢谢。
    猜你喜欢
    • 2016-08-22
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2015-01-30
    • 2018-09-11
    相关资源
    最近更新 更多