0

我需要将任意数据存储在多种数据类型的关系数据库中,所以我想出了一个解决方案,除了存储数据本身之外,还存储数据的数据类型(str、int 等)。这允许在检索时将存储在数据库中的字符串转换为数据的任何适当数据类型。为了存储数据类型,我创建了一个自定义模型字段:

class DataType(object):
    SUPPORTED_TYPES = {
        u'unicode': unicode,
        u'str': str,
        u'bool': bool,
        u'int': int,
        u'float': float
    }
    INVERSE_SUPPORTED_TYPES = dict(zip(SUPPORTED_TYPES.values(), SUPPORTED_TYPES.keys()))
    TYPE_CHOICES = dict(zip(SUPPORTED_TYPES.keys(), SUPPORTED_TYPES.keys()))

    def __init__(self, datatype=None):
        if not datatype:
            datatype = unicode

        t_datatype = type(datatype)

        if t_datatype in [str, unicode]:
            self.datatype = self.SUPPORTED_TYPES[datatype]

        elif t_datatype is type and datatype in self.INVERSE_SUPPORTED_TYPES.keys():
            self.datatype = datatype

        elif t_datatype is DataType:
            self.datatype = datatype.datatype

        else:
            raise TypeError('Unsupported %s' % str(t_datatype))

    def __unicode__(self):
        return self.INVERSE_SUPPORTED_TYPES[self.datatype]

    def __str__(self):
        return str(self.__unicode__())

    def __len__(self):
        return len(self.__unicode__())

    def __call__(self, *args, **kwargs):
        return self.datatype(*args, **kwargs)


class DataTypeField(models.CharField):
    __metaclass__ = models.SubfieldBase
    description = 'Field for storing python data-types in db with capability to get python the data-type back'

    def __init__(self, **kwargs):
        defaults = {}
        overwrites = {
            'max_length': 8
        }
        defaults.update(kwargs)
        defaults.update(overwrites)
        super(DataTypeField, self).__init__(**overwrites)

    def to_python(self, value):
        return DataType(value)

    def get_prep_value(self, value):
        return unicode(DataType(value))

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        return self.get_prep_value(val)

所以这让我可以做这样的事情:

class FooModel(models.Model):
    data = models.TextField()
    data_type = DataTypeField()

>>> foo = FooModel.objects.create(data='17.94', data_type=float)
>>> foo.data_type(foo.data)
17.94
>>> type(foo.data_type(foo.data))
float

所以我的问题是,在 Django Admin(我正在使用 ModelAdmin)中,文本框中 data_type 的值没有正确显示。无论何时float(并且在 db 中它存储为 float,我检查过),显示的值都是0.0. 因为int它显示0. 因为bool它显示False. 不是显示 data_type 的字符串表示,而是在 Django 实际调用它的地方,这意味着使用__call__我们的参数调用它,这会产生这些值。例如:

>>> DataType(float)()
0.0
>>> DataType(int)()
0
>>> DataType(bool)()
False

__call__我想出了如何通过用以下替换方法来修补它:

def __call__(self, *args, **kwargs):
    if not args and not kwargs:
        return self.__unicode__()
    return self.datatype(*args, **kwargs)

这会在表单中显示正确的值,但是我觉得这不是很优雅。有没有办法让它变得更好?我不知道 Django 一开始在哪里调用了字段值。

谢谢

4

1 回答 1

0

wrt 为什么调用您的 DataType,请阅读以下内容: https ://docs.djangoproject.com/en/1.4/topics/templates/#accessing-method-calls

干净的解决方案可能是简单地将调用重命名为更明确的名称。

于 2012-06-28T15:00:06.680 回答