你需要ALTER你Future表并为feature_value字段添加一个constraint这样的查询:
ALTER TABLE your_feature_table
ADD CONSTRAINT restricted_keys
CHECK (
-- Check that 'feature_value' contains all specified keys
feature_value::hstore ?& ARRAY['size', 'format', 'quality']
AND
-- and that number of keys is three
array_length(akeys(feature_value), 1) = 3
);
这将确保feature_value 中的每个数据都可以恰好包含三个键:大小、格式和质量;并且不允许空数据。
请注意,在应用此查询之前,您需要从表中删除所有无效数据,否则您会收到错误:
ERROR: check constraint "restricted_keys" is violated by some row
您可以在 DB 控制台中执行此查询,或者由于您使用的是 Django,因此更适合创建迁移并使用 RunSQL 应用此查询:创建一个 emtpy 迁移并将上述查询传递给 migrations.RunSQL ,并将此查询传递给reverse_sql 参数,以便在未应用迁移时删除约束:
ALTER TABLE your_feature_table
DROP CONSTRAINT restricted_keys;
申请后:
sql> INSERT INTO your_feature_table (feature_value) VALUES ('size => 124, quality => great, format => A4')
1 row affected in 18ms
sql> INSERT INTO your_feature_table (feature_value) VALUES ('format => A4')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("format"=>"A4").
sql> INSERT INTO your_feature_table (feature_value) VALUES ('')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ().
sql> INSERT INTO your_feature_table (feature_value) VALUES ('a => 124, b => great, c => A4')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("a"=>"124", "b"=>"great", "c"=>"A4").
sql> INSERT INTO your_feature_table (feature_value) VALUES ('size => 124, quality => great, format => A4, incorrect_key => error')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("size"=>"124", "format"=>"A4", "quality"=>"great", "incorrect_ke...).