Sometime we need to clean up the value before it validated by an exiting validations. For example, when user sended an longitude and latitude data into backend with multiple length variations. But, the client sended it data without any input form. And the backend we need to equalize into what backend needed and saved into database with valid format.

In django ModelSerializer, it called with def to_internal_value. In this function we can clean up the upcoming data first before it data is going to be validate with an exsisting validators. For example:

class AddressSerializer(serializers.ModelSerializer):

    def to_internal_value(self, data):

        # rounded up last digit with maximum decimal_places=6 digits.
        data['long'] = convert_long_lat(data['long'], 6)
        data['lat'] = convert_long_lat(data['lat'], 6)

        return super().to_internal_value(data)

    class Meta:
        model = Address
        fields = '__all__'

And for the cleaner or converter function of convert_long_lat, its like:

def convert_long_lat(long_lat, decimal_places=6):
    """
    function to convert the longitude or latitude
    into valide long or lat value, which following this issue:
    https://stackoverflow.com/a/1196429/6396981

    - longitude: Decimal(9,6)
    - latitude : Decimal(8,6)

    format string visual:
      (longitude)    (latitude)
      ###.###### and ##.######

    :param `long_lat` is string/float longitude/latitude.
    :param `decimal_places` is maximum decimal places after comma/dot (default=6).
    :return <str/float> of converted long/lat with maximum `decimal_places`.
    """

    try:
        floated = float(long_lat)
        rounded = round(floated, decimal_places)
        return type(long_lat)(rounded)
    except ValueError:
        # bypass an error and rollback
        # to the original `long_lat` value
        pass

    return long_lat
101 1 1 0