gpt4 book ai didi

django - 在 Postgresql 中限制数据库

转载 作者:搜寻专家 更新时间:2023-10-30 23:40:28 25 4
gpt4 key购买 nike

我正在使用 Django1.9 和 Postgresql。这是我的模型“特征”的数据模型:

class Feature(models.Model):
image_component = models.ForeignKey('Image_Component',on_delete=models.CASCADE,)
feature_value = HStoreField()

def save(self,*args,**kwargs):
if Feature.objects.filter(feature_value__has_keys=['size', 'quality' , 'format']):
super(Feature, self).save(*args, **kwargs)
else:
print("Incorrect key entered")

我对 feature_value 施加了限制,只有 Hstore 允许的键是 sizeformatquality。 我可以在使用 Django-Admin 更新数据库时执行此操作。但是我无法使用具有相同限制的 pgAdmin3 直接更新数据库,即,我想对数据库级别施加相同的限制。我怎样才能做到这一点?有什么建议吗?

最佳答案

您需要ALTERFuture 表并添加一个 constraint对于具有此类查询的 feature_value 字段:

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

您可以在数据库控制台中执行此查询,或者由于您使用的是 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...).

关于django - 在 Postgresql 中限制数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com