代码之家  ›  专栏  ›  技术社区  ›  l0b0

如何禁止在创建Django字段后更改?

  •  1
  • l0b0  · 技术社区  · 6 年前

    我有这样一个模型:

    THRESHOLD_CLASSES = {
        MinimumThreshold.name: MinimumThreshold,
        MaximumThreshold.name: MaximumThreshold
    }
    
    class Threshold(models.Model):
        thingie = models.ForeignKey(Thingie, models.CASCADE)
        threshold_types = THRESHOLD_CLASSES.keys()
        type = models.TextField(choices=zip(threshold_types, threshold_types))
        threshold = models.DecimalField()
    

    import abc
    import operator
    
    
    class Threshold(abc.ABC):
        @abc.abstractmethod
        def __init__(self):
            pass
    
    
    class MinimumThreshold(Threshold):
        name = 'minimum'
        operator = operator.lt
        operator_name = 'lower than'
    
        def __init__(self):
            self.other_class = MaximumThreshold
    
    
    class MaximumThreshold(Threshold):
        name = 'maximum'
        operator = operator.gt
        operator_name = 'greater than'
    
        def __init__(self):
            self.other_class = MinimumThreshold
    

    在我的序列化程序中,我必须验证 thingie 小于其最大值:

    def validate(self, instance):
        instance_type = instance['type']
        instance_threshold_class = models.THRESHOLD_CLASSES[instance_type]
        other_threshold_class = instance_threshold_class().other_class
        other = models \
            .AlarmParameterThreshold \
            .objects \
            .filter(thingie=instance['thingie'], type=other_threshold_class.name) \
            .first()
        if other:
            if other_threshold_class.operator(instance['threshold'], other.threshold):
                message = "The {} threshold cannot be {} the {} threshold of {}".format(
                    instance_type,
                    other_threshold_class.operator_name,
                    other_threshold_class.name,
                    other.threshold
                )
                raise serializers.ValidationError({'threshold': message})
    

    更改 type 现有的 Threshold

    在这种情况下,更简单的方法是 类型 一旦设定好, 但我不知道有什么方法比从比较中排除当前项目更容易。

    0 回复  |  直到 6 年前