postgresql - 布尔列上的 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)
解决方案
在 Postgres 中,您可以使用过滤的唯一索引来执行此操作:
create unique index on the_table (property_id)
where is_best;
推荐阅读
- filenet-p8 - 为 Filenet 形成 ExecuteSearch Soap 操作
- gcc - 未定义对“WinMain@16”错误的引用
- c# - 您无权查看此目录或页面未授权 401
- typescript - typescript 导出类型和模块值
- sql - 将 Table1 的所有记录复制到 Table2 中,并将单独的数据插入到 Table2 中
- java - 为什么在使用 SimpleDateFormat 解析字符串中的日期时会得到错误的结果?(爪哇)
- java - 使用流将集合拆分为在地图中分组的多个集合
- javascript - 同一组数据的两个图表 - Chart.js
- python - 如何按周聚合 Pandas 中的多级索引,以星期为列?
- sql - 仅在基础数据更改时重新计算的 SQL 计算表