postgresql_where 中的多个条件?

Ng *_*-Ee 6 postgresql sqlalchemy pyramid

postgresql_where对于绕过 Postgres 定义唯一性的方式(在我看来是错误的,但显然 SQL 标准定义它)很有用,其中 Null 值始终是唯一的。下面显示了一个典型示例,其中没有任何项目可以具有相同的名称+用途+batch_id 值(由于第二个索引,None/Null 被视为一个唯一值)。

class Item(StoredObject, Base):
    batch_id = Column(Integer, ForeignKey('batch.id'))
    group_id = Column(Integer, ForeignKey('group.id'))
    name = Column(Text, nullable=False)
    purpose = Column(Text, nullable=False, default="")
    __table_args__ = (
        Index('idx_batch_has_value',
              'group_id', 'name', 'purpose', 'batch_id',
              unique=True,
              postgresql_where=(batch_id.isnot(None))),
        Index('idx_batch_has_no_value',
              'group_id', 'name', 'purpose',
              unique=True,
              postgresql_where=(batch_id.is_(None))),
        )
Run Code Online (Sandbox Code Playgroud)

但是,我希望在两个 id(batch_id 和 group_id)中具有相同的行为,也就是说,没有任何项目可以具有相同的名称+用途+batch_id+group_id 值(None/Null 被认为是 batch_id 和 group_id 中的一个唯一值)。

我可以通过创建一个带有固定 ID(比如 0)的“默认”批处理/组对象来解决这个问题。这意味着我必须确保批处理/组对象存在,不能被删除,并且该 id 不会被重新分配给另一个“真正的”批处理/组对象(更不用说我必须记住使用/编写计算我有多少批次/组的函数时,将所有计数减一)。

可行,我现在就要做,但一定有更好的方法!有没有类似的东西:-

postgresql_where = (batch_id.isnot(None) AND group_id.isnot(None))
Run Code Online (Sandbox Code Playgroud)

这将解决我认为应该在数据库中而不是在我的模型和/或初始化代码中解决的问题。

flo*_*ter -2

from sqlalchemy import and_

postgresql_where=and_(batch_id.isnot(None), group_id.isnot(None))
Run Code Online (Sandbox Code Playgroud)