Values_list doesn't use to_python in user-defined model regions?

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?

+4
source share
2 answers

Answered my own question: this is apparently a Django bug. values_list does not deserialize database data.

Tracked here: https://code.djangoproject.com/ticket/9619 and is awaiting a constructive solution.

+3
source

Just note that this was allowed in Django 1.8 with the addition of the from_db_value method in custom fields.

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

0
source

Source: https://habr.com/ru/post/1391390/


All Articles