首页 > 解决方案 > 布尔列上的 sqlalchemy 约束以允许具有相同外键的多行单个 true

问题描述

我有下表

  id | property_id | photo_url | is_best 
 ----|-------------|-----------|--------- 
   1 |           1 | test1     | true    
   2 |           1 | test2     | false   
   3 |           1 | test3     | false   
   4 |           2 | mest1     | true    
   5 |           2 | mest2     | false   
   6 |           3 | jest1     | false   

其中 property_id 是外键。我需要一个约束来限制具有相同 property_id 的行上 is_best 列的多个真值

例如限制更新 is_best = True for id = 2 or id = 3 or where id = 5

理想情况下,我需要在 sqlalchemy 中使用此功能。但是 postgres 代码也很好。

我在 sqlalchemy 中创建表,如下所示:

class PropertyPhoto(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    property_id = db.Column(db.Integer,
                            db.ForeignKey('property.id'),
                            nullable=False,
                            onupdate='CASCADE',
                            ondelete='CASCADE')
    photo_url = db.Column(db.String, nullable=False, unique=True)
    is_best = db.Column(db.Boolean, default=False)

标签: postgresqlsqlalchemyflask-sqlalchemy

解决方案


在 Postgres 中,您可以使用过滤的唯一索引来执行此操作:

create unique index on the_table (property_id)
where is_best;

推荐阅读