因此,要在数据库中存储numpy.inf
或numpy.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
对象的方式。
我做错了什么?