values_list在自定义模型字段中不使用to_python?

问题描述:

我似乎偶然发现了Django自定义模型字段中的一个怪癖。我有以下自定义模式字段:values_list在自定义模型字段中不使用to_python?

class PriceField(models.DecimalField): 
    __metaclass__ = models.SubfieldBase 

    def to_python(self, value): 
     try: 
      return Price(super(PriceField, self).to_python(value)) 
     except (TypeError, AttributeError): 
      return None 

    def get_db_prep_value(self, value): 
     return super(PriceField, self).get_db_prep_value(value.d if value else value) 

    def value_to_string(self, instance): 
     return 'blah' 

应该总是返回python中的自定义Price类。这按预期工作:

>>> PricePoint.objects.all()[0].price 
Price('1.00') 

然而,在values_list的形式获取价格时,我得到小数回:

>>> PricePoint.objects.all().values_list('price') 
[(Decimal('1'),)] 

然后,如果我改变了DB类型foat,然后再试一次,我收到了浮动:

>>> PricePoint.objects.all().values_list('price') 
[(1.0,)] 
>>> type(PricePoint.objects.all().values_list('price')[0][0]) 
<type 'float'> 

这让我觉得values_list根本不依赖to_python,而只是返回数据库中定义的类型。那是对的吗?有没有办法通过values_list返回自定义类型?

回答了我自己的问题:这显然是一个Django错误。 values_list不反序列化数据库数据。

它在这里被跟踪:https://code.djangoproject.com/ticket/9619并且正在等待设计决定。

只是要注意,这是在Django 1.8中解决的,在自定义字段中增加了from_db_value方法。

请参阅https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/#converting-values-to-python-objects