I seem to have stumbled upon a fad in the fields of a custom Django model. I have the following custom modelfield:
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'
which should always return a custom Price class in python. This works as expected:
>>> PricePoint.objects.all()[0].price Price('1.00')
However, when I get prices as a list_value, I get the decimal places back:
>>> PricePoint.objects.all().values_list('price') [(Decimal('1'),)]
Then, if I change the database type to foat and try again, I get a float:
>>> PricePoint.objects.all().values_list('price') [(1.0,)] >>> type(PricePoint.objects.all().values_list('price')[0][0]) <type 'float'>
This makes me think that values_list does not rely on to_python at all and instead returns the type defined in the database. It's right? Is there a way to return a custom type via values_list?
source share