Numpy值的自定义Django模型字段,如' nan'和' inf'

时间:2015-11-19 15:34:59

标签: python django numpy

因此,要在数据库中存储numpy.infnumpy.nan等值,我创建了一个这样的自定义模型字段 -

import numpy as np
from django.db import models

INF = 1.79e308  # large arbitrary number


def convert_np_to_float(obj):
    if obj == np.nan:
        return None
    elif obj == np.inf:
        return INF
    elif obj == -np.inf:
        return -INF
    else:
        return obj

def convert_float_to_np(f):
    if f is None:
        return np.nan
    elif f >= INF or np.isclose(f, INF):
        return np.inf
    elif f <= -INF or np.isclose(f, -INF):
        return -np.inf
    else:
        return f

class NumpyFloatField(models.FloatField):

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('null', True)
        super(NumpyFloatField, self).__init__(*args, **kwargs)

    def get_prep_value(self, value):
        value = convert_np_to_float(value)
        return super(NumpyFloatField, self).get_prep_value(value)

    def to_python(self, value):
        value = super(NumpyFloatField, self).to_python(value)
        value = convert_float_to_np(value)
        return value


class CalculationResult(models.Model):
    calc_id = models.IntegerField(primary_key=True)
    result = NumpyFloatField()

现在对象得到了很好的保存 -

In [6]: c = CalculationResult.objects.create(calc_id=25, result=np.inf)  

In [7]: c.result
Out[7]: inf

但是当我稍后收到c.result时,numpy.inf -

In [2]: c = CalculationResult.objects.get(calc_id=25)

In [3]: c.result
Out[3]: 1.79e+308

我希望该字段返回numpy.inf而不是我选择在数据库中表示无穷大的值,有点像DateTimeField返回DateTime对象的方式。

我做错了什么?

0 个答案:

没有答案