Skip to content Skip to sidebar Skip to footer

Why Does Cloning This Subclass Of FloatField (with Added Validators) Throw An Exception?

I am new to Python and Django. I want my model to have range-validated floats. From this answer I wrote this: class FloatRangeField (FloatField): '''A FloatField constrained to

Solution 1:

Like is written in the documentation on custom model fields:

If you add a new keyword argument, you need to write code to put its value into kwargs yourself (...)

So you should add a deconstructor as well. This is necessary, for example to represent this field in a migration file:

class FloatRangeField (FloatField):
    """A FloatField constrained to a given range."""

    def __init__ (self, minimum, maximum, **kwargs):
        self.minimum = minimum
        self.maximum = maximum
        minmax = [MinValueValidator (minimum), MaxValueValidator (maximum)]
        FloatField.__init__ (self, validators = minmax, **kwargs)

    def deconstruct(self):
        result = __, __, __, kwargs = super(FloatRangeField, self).deconstruct()
        kwargs['minimum'] = self.minimum
        kwargs['minimum'] = self.maximum
        del kwargs['validators']
        return result

Note that you better do not use validators = minmax as parameter, since that will mean that if a user would use the validator parameters for your FloatRangeField constructor, there will be a parameter clash.

For example it is possible to append our minmax validators to the validators that already exist, and then later pop these back from the validator when we want to deconstruct it:

class FloatRangeField (FloatField):
    """A FloatField constrained to a given range."""

    def __init__ (self, minimum, maximum, **kwargs):
        self.minimum = minimum
        self.maximum = maximum
        old_validators = kwargs.get('validators', [])
        minmax = [MinValueValidator (minimum), MaxValueValidator (maximum)]
        minmax += old_validators
        kwargs['validators'] = minmax
        FloatField.__init__ (self, **kwargs)
    

    def deconstruct(self):
        result = __, __, __, kwargs = super(FloatRangeField, self).deconstruct()
        kwargs['minimum'] = self.minimum
        kwargs['minimum'] = self.maximum
        kwargs['validators'] = kwargs['validators'][2:]
        return result

So here we in the deconstruct(..) function, we remove the first two validators (that we added in the __init__(..) function).


Post a Comment for "Why Does Cloning This Subclass Of FloatField (with Added Validators) Throw An Exception?"