Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django自定义十进制字段-实现自动浮点到双精度转换的最佳方法?_Python_Django_Custom Fields_Decimalformat_Django Custom Field - Fatal编程技术网

Python Django自定义十进制字段-实现自动浮点到双精度转换的最佳方法?

Python Django自定义十进制字段-实现自动浮点到双精度转换的最佳方法?,python,django,custom-fields,decimalformat,django-custom-field,Python,Django,Custom Fields,Decimalformat,Django Custom Field,当我使用DecimalField时,数据库中几乎没有位置。不幸的是,我不得不将double和float数据作为输入来处理——这就是我的问题 我想做的是切掉数值(小数点后第二位),而不是一轮数学运算。我存储的计算值几乎不超过目标(如果我的值为49.9832100000032131,它仍然小于50,所以我不会对其进行取整)。但正如我所说的——我想在数据库中将其保存为48.98(小数点后两位)——节省内存和足够的表示 我的第一个解决方案是使用自定义django字段,类似于: class Decimal

当我使用DecimalField时,数据库中几乎没有位置。不幸的是,我不得不将double和float数据作为输入来处理——这就是我的问题

我想做的是切掉数值(小数点后第二位),而不是一轮数学运算。我存储的计算值几乎不超过目标(如果我的值为49.9832100000032131,它仍然小于50,所以我不会对其进行取整)。但正如我所说的——我想在数据库中将其保存为48.98(小数点后两位)——节省内存和足够的表示

我的第一个解决方案是使用自定义django字段,类似于:

class DecimalFixedField(models.DecimalField):

def __init__(self, *args, **kwargs):
    kwargs['value'] = "{0:.2f}".format( kwargs['value'] )            
    # or ? self.value = "{0:.2f}".format( kwargs['value'] )
    super(DecimalFixedField, self).__init__(*args, **kwargs)
class DecimalFixedField(models.DecimalField):

    def pre_save(self, model_instance, add):

        # reading value
        value_field = getattr(model_instance, self.attname)

        # casting to decimal if the value is not a decimal (float for example)
        if not isinstance(value_field, decimal.Decimal):
            value_field = decimal.Decimal(str(value_field))

        # there you can cut off the value
        quantized_value = value_field.quantize(decimal.Decimal(str(0.1**self.decimal_places)), rounding=decimal.ROUND_DOWN)

        # saving value
        setattr(model_instance, self.attname, quantized_value)
        return quantized_value
当然,我应该在kwargs中硬编码decimal_places=2,或者在代码中使用它,而不是值2,但是。。。休息呢?你有更好的建议吗

重要的是-我不想在代码的许多地方编写“{0:.2f}”.format(…)!我想用面向对象的方法来实现它,因为我在许多模型中使用了DecimalField。。。使这个预处理看起来是一个很好的解决方案。您认为应该如何正确地实施它吗?

尝试使用以下方法:

from decimal import Decimal

my_value = Decimal(value) 
尝试使用以下方法:

from decimal import Decimal

my_value = Decimal(value) 

经过思考和尝试,我做了如下事情:

class DecimalFixedField(models.DecimalField):

def __init__(self, *args, **kwargs):
    kwargs['value'] = "{0:.2f}".format( kwargs['value'] )            
    # or ? self.value = "{0:.2f}".format( kwargs['value'] )
    super(DecimalFixedField, self).__init__(*args, **kwargs)
class DecimalFixedField(models.DecimalField):

    def pre_save(self, model_instance, add):

        # reading value
        value_field = getattr(model_instance, self.attname)

        # casting to decimal if the value is not a decimal (float for example)
        if not isinstance(value_field, decimal.Decimal):
            value_field = decimal.Decimal(str(value_field))

        # there you can cut off the value
        quantized_value = value_field.quantize(decimal.Decimal(str(0.1**self.decimal_places)), rounding=decimal.ROUND_DOWN)

        # saving value
        setattr(model_instance, self.attname, quantized_value)
        return quantized_value

也许这对某人会有帮助:)

经过思考和尝试,我做了如下事情:

class DecimalFixedField(models.DecimalField):

def __init__(self, *args, **kwargs):
    kwargs['value'] = "{0:.2f}".format( kwargs['value'] )            
    # or ? self.value = "{0:.2f}".format( kwargs['value'] )
    super(DecimalFixedField, self).__init__(*args, **kwargs)
class DecimalFixedField(models.DecimalField):

    def pre_save(self, model_instance, add):

        # reading value
        value_field = getattr(model_instance, self.attname)

        # casting to decimal if the value is not a decimal (float for example)
        if not isinstance(value_field, decimal.Decimal):
            value_field = decimal.Decimal(str(value_field))

        # there you can cut off the value
        quantized_value = value_field.quantize(decimal.Decimal(str(0.1**self.decimal_places)), rounding=decimal.ROUND_DOWN)

        # saving value
        setattr(model_instance, self.attname, quantized_value)
        return quantized_value

也许这会对某人有所帮助:)

我知道这一点,但正如我所说的-我有8款使用DecimalField和。。。我想用优雅的方式——在一个地方。不是在每一个新模型中,也不是在每一个可以将浮点值保存到DecimalField中的代码中:),虽然此代码可以回答这个问题,但提供关于为什么和/或如何回答这个问题的附加上下文将显著提高其长期价值。请你的回答补充一些解释。我知道这一点,但正如我所说的-我有8个模型使用DecimalField和。。。我想用优雅的方式——在一个地方。不是在每一个新模型中,也不是在每一个可以将浮点值保存到DecimalField中的代码中:),虽然此代码可以回答这个问题,但提供关于为什么和/或如何回答这个问题的附加上下文将显著提高其长期价值。请在您的回答中添加一些解释。